> ## Documentation Index
> Fetch the complete documentation index at: https://docs.winnerr.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Twilio Integration

> Complete guide to integrating Twilio for SMS, voice calls, and video communications in your real estate CRM

Winnerr's Twilio integration provides comprehensive communication capabilities including SMS messaging, voice calls, voicemail, call recording, and video conferencing. This integration enables real estate professionals to manage all client communications from a single platform.

## Integration Features

<CardGroup cols={2}>
  <Card title="SMS Messaging" icon="message-square">
    Send individual and bulk SMS messages with templates and automation
  </Card>

  <Card title="Voice Calling" icon="phone">
    Make and receive calls with recording, transcription, and call forwarding
  </Card>

  <Card title="Video Conferencing" icon="video">
    Host virtual property tours and client meetings with screen sharing
  </Card>

  <Card title="Advanced Features" icon="settings">
    Call routing, IVR systems, conference calls, and analytics
  </Card>
</CardGroup>

## Setup & Configuration

### 1. Twilio Account Setup

Before integrating with Winnerr, you'll need a Twilio account:

1. **Create Twilio Account**: Visit [twilio.com](https://www.twilio.com) and sign up
2. **Get Account SID**: Found in your Twilio Console dashboard
3. **Generate Auth Token**: Create a new auth token for API access
4. **Purchase Phone Number**: Buy a dedicated phone number for your business

### 2. Integration Configuration

Configure the Twilio integration in your Winnerr settings:

```javascript theme={null}
// Example: Twilio integration setup
const twilioConfig = {
  accountSid: 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  authToken: 'your_auth_token',
  phoneNumber: '+1234567890',
  settings: {
    enableSms: true,
    enableVoice: true,
    enableVideo: false,
    autoRecordCalls: true,
    forwardingEnabled: true,
    voicemailEnabled: true,
    transcriptionEnabled: true
  }
};
```

### 3. Webhook Configuration

Set up webhooks to receive real-time updates from Twilio:

```javascript theme={null}
// Webhook endpoints for Twilio events
const webhookEndpoints = {
  sms: 'https://your-app.com/webhooks/twilio/sms',
  voice: 'https://your-app.com/webhooks/twilio/voice',
  recording: 'https://your-app.com/webhooks/twilio/recording',
  status: 'https://your-app.com/webhooks/twilio/status'
};
```

## SMS Messaging

### Individual SMS

Send personalized SMS messages to contacts:

```javascript theme={null}
// Example: Send individual SMS
const sendSms = async (contactId, message) => {
  const response = await fetch('/api/twilio/sms/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      to: contactId,
      message: message,
      template: 'property_inquiry_followup'
    })
  });
  
  return response.json();
};
```

### Bulk SMS Campaigns

Send SMS campaigns to multiple contacts:

```javascript theme={null}
// Example: Bulk SMS campaign
const sendBulkSms = async (campaign) => {
  const response = await fetch('/api/twilio/sms/bulk', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      recipients: campaign.contacts,
      message: campaign.message,
      template: campaign.template,
      scheduledAt: campaign.scheduledAt,
      personalization: true
    })
  });
  
  return response.json();
};
```

### SMS Templates

Create and manage SMS templates for common scenarios:

```javascript theme={null}
// Example SMS templates
const smsTemplates = {
  welcome: {
    name: 'Welcome Message',
    content: 'Hi {{firstName}}! Welcome to {{agentName}}. I\'m excited to help you find your dream home. Reply STOP to opt out.',
    variables: ['firstName', 'agentName']
  },
  property_update: {
    name: 'Property Update',
    content: 'New property matching your criteria: {{propertyAddress}} - ${{price}}. View details: {{propertyUrl}}',
    variables: ['propertyAddress', 'price', 'propertyUrl']
  },
  appointment_reminder: {
    name: 'Appointment Reminder',
    content: 'Reminder: Property showing tomorrow at {{time}} for {{propertyAddress}}. See you there!',
    variables: ['time', 'propertyAddress']
  }
};
```

### SMS Automation

Set up automated SMS workflows:

```javascript theme={null}
// Example: SMS automation workflow
const smsAutomation = {
  trigger: 'contact_created',
  conditions: [
    { field: 'source', operator: 'equals', value: 'website' },
    { field: 'leadScore', operator: 'greater_than', value: 50 }
  ],
  actions: [
    {
      type: 'send_sms',
      template: 'welcome',
      delay: 0
    },
    {
      type: 'send_sms',
      template: 'property_recommendations',
      delay: 3600 // 1 hour
    }
  ]
};
```

## Voice Calling

### Making Calls

Initiate outbound calls through the Winnerr interface:

```javascript theme={null}
// Example: Make outbound call
const makeCall = async (contactId, callSettings) => {
  const response = await fetch('/api/twilio/calls/initiate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      to: contactId,
      record: callSettings.record,
      transcribe: callSettings.transcribe,
      timeout: callSettings.timeout || 30
    })
  });
  
  return response.json();
};
```

### Call Forwarding

Configure call forwarding rules:

```javascript theme={null}
// Example: Call forwarding configuration
const callForwarding = {
  enabled: true,
  rules: [
    {
      condition: 'business_hours',
      action: 'forward_to_agent',
      agentId: 'agent_123'
    },
    {
      condition: 'after_hours',
      action: 'forward_to_voicemail',
      greeting: 'Thank you for calling. Please leave a message.'
    },
    {
      condition: 'agent_busy',
      action: 'forward_to_team',
      teamId: 'team_456'
    }
  ]
};
```

### Call Recording & Transcription

Enable call recording and automatic transcription:

```javascript theme={null}
// Example: Call recording settings
const recordingSettings = {
  autoRecord: true,
  transcribeRecordings: true,
  transcriptionCallback: '/api/twilio/transcription/callback',
  recordingCallback: '/api/twilio/recording/callback',
  retentionPeriod: 365, // days
  encryptRecordings: true
};
```

### IVR (Interactive Voice Response)

Set up IVR menus for professional call handling:

```javascript theme={null}
// Example: IVR configuration
const ivrMenu = {
  greeting: 'Thank you for calling Premier Realty. Your call is important to us.',
  options: [
    {
      key: '1',
      description: 'For property inquiries',
      action: 'forward_to_agent',
      departmentId: 'sales'
    },
    {
      key: '2',
      description: 'For existing clients',
      action: 'forward_to_agent',
      departmentId: 'client_services'
    },
    {
      key: '3',
      description: 'For general information',
      action: 'play_message',
      message: 'Our office hours are Monday through Friday, 9 AM to 6 PM.'
    },
    {
      key: '0',
      description: 'To speak with an operator',
      action: 'forward_to_operator'
    }
  ]
};
```

## Video Conferencing

### Virtual Property Tours

Host virtual property tours using Twilio Video:

```javascript theme={null}
// Example: Create virtual tour room
const createVirtualTour = async (propertyId, participants) => {
  const response = await fetch('/api/twilio/video/rooms', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      propertyId: propertyId,
      roomType: 'group',
      participants: participants,
      features: {
        screenShare: true,
        recording: true,
        maxParticipants: 10
      }
    })
  });
  
  return response.json();
};
```

### Client Meetings

Schedule and host client meetings:

```javascript theme={null}
// Example: Schedule video meeting
const scheduleVideoMeeting = async (meetingDetails) => {
  const response = await fetch('/api/twilio/video/meetings', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      title: meetingDetails.title,
      scheduledAt: meetingDetails.scheduledAt,
      duration: meetingDetails.duration,
      participants: meetingDetails.participants,
      settings: {
        requireAuth: true,
        recording: true,
        waitingRoom: true
      }
    })
  });
  
  return response.json();
};
```

## Advanced Features

### Conference Calls

Set up conference calls for team collaboration:

```javascript theme={null}
// Example: Create conference call
const createConference = async (conferenceDetails) => {
  const response = await fetch('/api/twilio/conferences', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      name: conferenceDetails.name,
      participants: conferenceDetails.participants,
      settings: {
        record: true,
        moderatorRequired: true,
        waitUrl: 'https://your-app.com/wait-music.mp3'
      }
    })
  });
  
  return response.json();
};
```

### Number Lookup

Verify and enrich phone number information:

```javascript theme={null}
// Example: Phone number lookup
const lookupPhoneNumber = async (phoneNumber) => {
  const response = await fetch('/api/twilio/lookup', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      phoneNumber: phoneNumber,
      includeCarrier: true,
      includeCallerName: true
    })
  });
  
  return response.json();
};
```

### Phone Number Management

Manage your Twilio phone numbers:

```javascript theme={null}
// Example: Phone number management
const phoneNumberManagement = {
  // Purchase new number
  purchaseNumber: async (areaCode) => {
    const response = await fetch('/api/twilio/phone-numbers/purchase', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_TOKEN'
      },
      body: JSON.stringify({
        areaCode: areaCode,
        capabilities: ['voice', 'sms'],
        friendlyName: `Office Line - ${areaCode}`
      })
    });
    
    return response.json();
  },
  
  // Configure number
  configureNumber: async (phoneNumber, config) => {
    const response = await fetch('/api/twilio/phone-numbers/configure', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_TOKEN'
      },
      body: JSON.stringify({
        phoneNumber: phoneNumber,
        voiceUrl: config.voiceUrl,
        smsUrl: config.smsUrl,
        statusCallback: config.statusCallback
      })
    });
    
    return response.json();
  }
};
```

## Analytics & Reporting

### Communication Analytics

Track communication performance and metrics:

```javascript theme={null}
// Example: Get communication analytics
const getCommunicationAnalytics = async (dateRange) => {
  const response = await fetch('/api/twilio/analytics', {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    params: {
      startDate: dateRange.startDate,
      endDate: dateRange.endDate,
      metrics: ['sms_sent', 'calls_made', 'call_duration', 'response_rate']
    }
  });
  
  return response.json();
};
```

### Call Quality Metrics

Monitor call quality and performance:

```javascript theme={null}
// Example: Call quality metrics
const callQualityMetrics = {
  overallQuality: 4.2,
  averageCallDuration: 420, // seconds
  callCompletionRate: 0.85,
  issueBreakdown: {
    audioQuality: 0.02,
    connectionIssues: 0.01,
    dropCalls: 0.03
  },
  recommendations: [
    'Consider upgrading internet connection',
    'Use headset for better audio quality'
  ]
};
```

## Error Handling & Troubleshooting

### Common Issues

**SMS Delivery Failures:**

```javascript theme={null}
// Example: Handle SMS delivery failures
const handleSmsError = (error) => {
  switch (error.code) {
    case 21211:
      console.log('Invalid phone number format');
      break;
    case 21614:
      console.log('Phone number not verified');
      break;
    case 21408:
      console.log('Permission denied for this number');
      break;
    default:
      console.log('Unknown SMS error:', error.message);
  }
};
```

**Call Connection Issues:**

```javascript theme={null}
// Example: Handle call connection issues
const handleCallError = (error) => {
  switch (error.code) {
    case 31003:
      console.log('Unreachable phone number');
      break;
    case 31005:
      console.log('Call busy');
      break;
    case 31008:
      console.log('Call rejected');
      break;
    default:
      console.log('Unknown call error:', error.message);
  }
};
```

### Retry Logic

Implement retry logic for failed operations:

```javascript theme={null}
// Example: Retry logic for SMS
const sendSmsWithRetry = async (message, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const result = await sendSms(message);
      return result;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // Exponential backoff
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};
```

## Security & Compliance

### Data Protection

Ensure compliance with data protection regulations:

```javascript theme={null}
// Example: Data protection settings
const dataProtectionSettings = {
  encryption: {
    recordings: true,
    transcriptions: true,
    messages: true
  },
  retention: {
    recordings: 365, // days
    transcriptions: 365,
    messages: 1095
  },
  access: {
    roleBasedPermissions: true,
    auditLogging: true,
    dataExport: true
  }
};
```

### Webhook Security

Secure webhook endpoints:

```javascript theme={null}
// Example: Webhook signature verification
const verifyWebhookSignature = (payload, signature, authToken) => {
  const crypto = require('crypto');
  const expectedSignature = crypto
    .createHmac('sha1', authToken)
    .update(payload)
    .digest('base64');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
};
```

## Best Practices

### 1. Message Templates

Create professional, compliant message templates:

```javascript theme={null}
// Best practice: Template structure
const professionalTemplate = {
  greeting: 'Hi {{firstName}}',
  body: '{{message}}',
  signature: '{{agentName}} - {{companyName}}',
  optOut: 'Reply STOP to opt out',
  compliance: {
    includeOptOut: true,
    businessHoursOnly: true,
    respectDoNotCall: true
  }
};
```

### 2. Call Routing

Implement intelligent call routing:

```javascript theme={null}
// Best practice: Smart call routing
const intelligentRouting = {
  rules: [
    {
      condition: 'vip_client',
      action: 'priority_queue',
      maxWaitTime: 30
    },
    {
      condition: 'business_hours',
      action: 'route_to_available_agent'
    },
    {
      condition: 'after_hours',
      action: 'voicemail_with_callback'
    }
  ]
};
```

### 3. Performance Monitoring

Monitor communication performance:

```javascript theme={null}
// Best practice: Performance monitoring
const performanceMonitoring = {
  metrics: {
    responseTime: 'under_24_hours',
    callbackRate: 'above_80_percent',
    customerSatisfaction: 'above_4_stars'
  },
  alerts: {
    deliveryFailures: 'immediate',
    callQualityIssues: 'immediate',
    highVolume: 'hourly'
  }
};
```

### 4. Compliance Management

Ensure regulatory compliance:

```javascript theme={null}
// Best practice: Compliance checklist
const complianceChecklist = {
  tcpa: {
    consentRequired: true,
    optOutMechanism: true,
    timeRestrictions: true
  },
  gdpr: {
    dataMinimization: true,
    rightToErasure: true,
    consentManagement: true
  },
  industry: {
    realEstateLicensing: true,
    fairHousing: true,
    truthInAdvertising: true
  }
};
```

## Integration Examples

### Lead Follow-up Automation

```javascript theme={null}
// Example: Automated lead follow-up
const leadFollowupAutomation = {
  trigger: 'new_lead_created',
  sequence: [
    {
      delay: 0,
      action: 'send_sms',
      template: 'welcome_message'
    },
    {
      delay: 3600, // 1 hour
      action: 'make_call',
      maxAttempts: 3
    },
    {
      delay: 86400, // 24 hours
      action: 'send_sms',
      template: 'property_recommendations'
    }
  ]
};
```

### Property Showing Coordination

```javascript theme={null}
// Example: Property showing coordination
const propertyShowingWorkflow = {
  trigger: 'showing_scheduled',
  actions: [
    {
      action: 'send_sms_to_client',
      template: 'showing_confirmation',
      timing: 'immediate'
    },
    {
      action: 'send_sms_reminder',
      template: 'showing_reminder',
      timing: '24_hours_before'
    },
    {
      action: 'create_conference_call',
      participants: ['client', 'agent', 'seller_agent'],
      timing: 'during_showing'
    }
  ]
};
```

***

<Note>
  The Twilio integration requires a valid Twilio account and phone number. All communications are logged for compliance and can be accessed through the Winnerr dashboard. Message and call rates apply according to your Twilio plan.
</Note>
