Skip to main content

📱 SMS Messaging System

Overview

Comprehensive SMS messaging system powered by Twilio with template support, delivery tracking, and analytics.

Features

✅ Completed Features

  • Twilio Integration: Reliable SMS delivery through Twilio API
  • Template System: Dynamic message templates with variable substitution
  • Delivery Tracking: Real-time delivery status monitoring
  • Phone Validation: E.164 format normalization and validation
  • Rate Limiting: Client-side rate limiting (10/min, 100/hour, 500/day)
  • Error Handling: Comprehensive error handling with retry logic
  • Analytics Integration: Message delivery and engagement tracking

🔄 In Progress

  • Message Scheduling: Delayed and scheduled message delivery
  • Bulk Messaging: Mass messaging capabilities for campaigns
  • Message Templates: Pre-built templates for common scenarios

📋 Planned

  • Two-Way SMS: Customer response handling and conversation management
  • SMS Shortcodes: Dedicated shortcode for premium messaging
  • International SMS: Global SMS delivery support

Architecture

Components

SMS System
├── Frontend Components
│ ├── SMSComposer.tsx
│ ├── MessageTemplates.tsx
│ └── DeliveryStatus.tsx
├── Backend Functions
│ ├── sendCustomMessageV2
│ ├── smsStatusCallback
│ └── messageAnalytics
└── External Services
├── Twilio API
├── Webhook Handlers
└── Analytics Tracking

Data Flow

  1. Message Composition: User creates message with template
  2. Phone Validation: Normalize and validate phone number
  3. Rate Limiting: Check client-side rate limits
  4. Twilio Processing: Send message through Twilio API
  5. Delivery Tracking: Monitor delivery status via webhooks
  6. Analytics Update: Track delivery and engagement metrics

Template System

Available Variables

// Visit Information
{{ticketNumber}} - Visit ticket number
{{keyId}} - Key mapping ID
{{siteName}} - Site name
{{orgName}} - Organization name
{{status}} - Current visit status

// Customer Information
{{customerName}} - Customer name
{{phone}} - Customer phone number

// Vehicle Information
{{make}} - Car make
{{model}} - Car model
{{color}} - Car color
{{plate}} - License plate

// Staff Information
{{dropOffValetName}} - Drop-off valet name
{{pickUpValetName}} - Pick-up valet name

// Timing Information
{{arrivedAt}} - Arrival time
{{parkedAt}} - Parking time
{{returnInProgressAt}} - Return start time
{{completedAt}} - Completion time
{{timeSinceArrival}} - Time since arrival

// Payment Information
{{price}} - Visit price
{{amount}} - Total amount
{{tip}} - Tip amount
{{totalAmount}} - Final total
{{invoiceNumber}} - Invoice number

// Links
{{myVisitsLink}} - Customer visits page
{{payLink}} - Payment page
{{payWithTicketLink}} - Payment with ticket
{{homeLink}} - Home page

Template Examples

// Car Arrival Notification
"🚗 Your car has arrived at {{siteName}}. Ticket #{{ticketNumber}}. We'll park it shortly. Track your visit: {{myVisitsLink}}"

// Car Ready Notification
"🔑 Your {{make}} {{model}} is ready for pickup at {{siteName}}. Ticket #{{ticketNumber}}. Please arrive within 5 minutes. Pay here: {{payWithTicketLink}}"

// Visit Complete Notification
"✅ Visit complete! Thank you for using {{orgName}} valet service. Total: {{totalAmount}}. Invoice: {{invoiceNumber}}"

API Endpoints

Send Custom Message

POST /sendCustomMessageV2
{
"phoneNumber": "+1234567890",
"messageBody": "Your car is ready!"
}

SMS Status Callback

POST /smsStatusCallback
// Twilio webhook payload
{
"MessageSid": "SMxxx",
"MessageStatus": "delivered",
"ErrorCode": "",
"ErrorMessage": ""
}

Configuration

Environment Variables

TWILIO_ACCOUNT_SID=AC...
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=+1234567890

Firebase Configuration

// Firebase Functions secrets
TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN
TWILIO_PHONE_NUMBER

Twilio Webhook Configuration

// Webhook URL for status callbacks
https://us-central1-PROJECT_ID.cloudfunctions.net/smsStatusCallback

Rate Limiting

Client-Side Limits

  • Per Minute: 10 messages
  • Per Hour: 100 messages
  • Per Day: 500 messages

Server-Side Protection

  • Twilio account-level rate limits
  • Function execution limits
  • Database write protection

Delivery Tracking

Status Types

  • sent: Message sent to carrier
  • delivered: Message delivered to recipient
  • failed: Message delivery failed
  • undelivered: Message could not be delivered

Tracking Implementation

// Store message for tracking
await admin.firestore().collection('sms_messages').doc(sid).set({
sid,
phoneNumber,
messageBody,
userId,
status: 'sent',
createdAt: admin.firestore.FieldValue.serverTimestamp()
});

// Update status via webhook
await admin.firestore().collection('sms_messages').doc(MessageSid).update({
status: MessageStatus,
errorCode: ErrorCode,
updatedAt: admin.firestore.FieldValue.serverTimestamp()
});

Analytics

Tracked Metrics

  • Delivery Rates: Success/failure rates by message type
  • Engagement: Click-through rates on links
  • Performance: Delivery times and response rates
  • Cost Analysis: SMS costs and ROI tracking

Analytics Events

// Message sent
analyticsService.trackSMSMessage('message_sent', {
messageType: 'status_update',
phoneNumber: phoneNumber,
messageLength: messageBody.length
});

// Delivery status
analyticsService.trackSMSMessage('message_delivered', {
messageId: sid,
deliveryTime: deliveryTime,
status: 'delivered'
});

Testing

Unit Tests

  • Message composition and validation
  • Phone number normalization
  • Template variable substitution
  • Rate limiting logic

Integration Tests

  • Twilio API integration
  • Webhook processing
  • Delivery status updates
  • Error handling scenarios

Manual Testing

  • End-to-end message flow
  • Template rendering
  • Delivery tracking
  • Error scenarios

Monitoring

Key Metrics

  • Message delivery rate
  • Average delivery time
  • Error rates by type
  • Cost per message

Alerts

  • Delivery failures > 10%
  • High error rates
  • Webhook failures
  • Rate limit exceeded

Troubleshooting

Common Issues

Message Not Delivered

  • Check phone number format
  • Verify Twilio account status
  • Check carrier delivery issues
  • Validate message content

Webhook Not Receiving Updates

  • Verify webhook URL configuration
  • Check Twilio signature validation
  • Monitor function logs
  • Test webhook endpoint

Rate Limiting Issues

  • Check client-side rate limits
  • Verify Twilio account limits
  • Monitor function execution limits
  • Review usage patterns

Debug Commands

# Check Twilio logs
twilio api:core:messages:list

# Test webhook locally
ngrok http 5001
# Update Twilio webhook URL to ngrok URL

# View message details
twilio api:core:messages:fetch --sid SMxxx

Future Enhancements

Short Term

  • Message scheduling and automation
  • Bulk messaging capabilities
  • Enhanced template editor
  • Delivery optimization

Long Term

  • Two-way SMS conversations
  • AI-powered message optimization
  • International SMS support
  • Rich media messaging (MMS)

SMS system ready for production! 📱