Saltar al contenido principal

WhatsApp Template Implementation Summary

🎯 Overview

We've successfully updated the Multi-Channel Communication System to support WhatsApp Message Templates, resolving the Error 63016: "Failed to send freeform message because you are outside the allowed window" issue.


✅ What Was Implemented

1. Database Schema Update

  • Added provider_template_id column to communication_template table
  • Stores WhatsApp template SIDs from Twilio Content API (format: HXe835f49d0aa7f1639f7f8e4b8a1e6c1e)

2. TypeScript Types Updated

  • Added providerTemplateId field to CommunicationTemplate interface
  • Updated all related types and DTOs

3. DTOs Enhanced

  • CreateTemplateDto: Added providerTemplateId field
  • SendCommunicationDto: Added providerTemplateId field

4. WhatsApp Adapter Refactored

  • Dual Mode Support:
    • Template Messages: Uses Twilio Content API with contentSid
    • Freeform Messages: Uses regular Twilio Messages API (24-hour window only)
  • Automatically detects which mode to use based on providerTemplateId presence
  • Proper variable mapping for Twilio Content API

5. Communications Service Updated

  • Fetches template from database to get providerTemplateId
  • For WhatsApp + template: Uses provider template instead of rendering
  • For other channels: Continues to render templates normally
  • Passes providerTemplateId through the queue to the adapter

6. Documentation Created

  • whatsapp-templates-setup-guide.md: Complete guide for setting up WhatsApp templates in Twilio
  • whatsapp-template-implementation-summary.md (this file): Implementation summary

🚀 How It Works

Sending Flow:

1. User calls /communications/send with:
- channel: "whatsapp"
- templateId: "uuid-of-template"
- templateVariables: {"1": "John", "2": "INV-001", ...}

2. CommunicationsService:
- Fetches template from database
- Checks if template has providerTemplateId
- If yes: Sets providerTemplateId for WhatsApp
- If no: Renders template normally

3. Communication queued with providerTemplateId

4. Queue processes communication

5. WhatsAppAdapterService:
- Detects providerTemplateId is set
- Calls sendTemplateMessage()
- Uses Twilio Content API with contentSid
- Maps templateVariables to Twilio format

6. Message sent via approved WhatsApp template ✅

📋 Setup Steps (Quick Reference)

For Developers

  1. Run Migration:

    cd packages/backend/database
    npm run migrate:up
  2. Rebuild Backend:

    cd apps/backend
    npm run build
  3. Restart Services:

    # Restart your backend server

For Business Users

  1. Create WhatsApp Templates in Twilio:

    • Follow guide: whatsapp-templates-setup-guide.md
    • Submit templates for approval
    • Wait for Meta/WhatsApp approval (1-24 hours)
  2. Get Content SID:

    • Copy from Twilio Console after approval
    • Format: HXe835f49d0aa7f1639f7f8e4b8a1e6c1e
  3. Update FlowPOS Templates:

    curl -X PATCH 'https://api.flowpos.com/communication-templates/{id}' \
    -H 'Authorization: Bearer TOKEN' \
    -H 'Content-Type: application/json' \
    -d '{
    "providerTemplateId": "HXe835f49d0aa7f1639f7f8e4b8a1e6c1e"
    }'
  4. Send WhatsApp Messages:

    • Messages automatically use templates
    • No code changes needed
    • Works outside 24-hour window

🎨 Example Usage

Before (Failed with Error 63016):

# Sending freeform message - FAILS outside 24-hour window
curl -X POST 'https://api.flowpos.com/communications/send' \
-H 'Authorization: Bearer TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"channel": "whatsapp",
"recipientContact": "+50256917111",
"content": "Your invoice is ready" # ❌ Fails!
}'

After (Works with Templates):

# Sending template message - WORKS anytime
curl -X POST 'https://api.flowpos.com/communications/send' \
-H 'Authorization: Bearer TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"businessId": "uuid",
"createdBy": "uuid",
"channel": "whatsapp",
"type": "invoice",
"recipientType": "customer",
"recipientId": "uuid",
"recipientContact": "+50256917111",
"templateId": "uuid-of-invoice-template",
"templateVariables": {
"1": "John Doe",
"2": "INV-001",
"3": "$150.00",
"4": "2025-11-01"
}
}' # ✅ Works!

📊 Database Changes

communication_template Table:

-- New column added
ALTER TABLE communication_template
ADD COLUMN provider_template_id VARCHAR;

-- Example data
UPDATE communication_template
SET provider_template_id = 'HXe835f49d0aa7f1639f7f8e4b8a1e6c1e'
WHERE code = 'invoice_whatsapp';

🔍 Code Changes Summary

Files Modified:

  1. Migration:

    • packages/backend/database/src/migrations/2025-10-24t00:25:51.900z-communication-system.mjs
    • Added provider_template_id column
  2. Types:

    • packages/backend/database/src/types/database.types.ts
    • Added providerTemplateId: string | null
  3. DTOs:

    • apps/backend/src/communication-templates/interfaces/dtos/create-template.dto.ts
    • apps/backend/src/communications/interfaces/dtos/send-communication.dto.ts
    • Added providerTemplateId field
  4. Services:

    • apps/backend/src/communications/application/communications.service.ts
    • Fetches and passes providerTemplateId
  5. Adapters:

    • apps/backend/src/communications/application/adapters/whatsapp-adapter.service.ts
    • Refactored to support both template and freeform messages

🎯 Benefits

For Users:

  • ✅ Send WhatsApp messages anytime (no 24-hour window restriction)
  • ✅ Professional, consistent messaging
  • ✅ Higher delivery rates
  • ✅ Better customer experience

For Developers:

  • ✅ Clean, maintainable code
  • ✅ Clear separation of concerns
  • ✅ Backward compatible (freeform still works within 24 hours)
  • ✅ Comprehensive logging

For Business:

  • ✅ Compliant with WhatsApp Business policies
  • ✅ Scalable messaging solution
  • ✅ Better customer engagement
  • ✅ Reduced support tickets

⚠️ Important Notes

Template Requirements:

  • Must be approved by Meta/WhatsApp
  • Approval takes 1-24 hours
  • Follow WhatsApp template guidelines
  • Test thoroughly before production

Variable Mapping:

  • Variables are numbered: 1, 2, 3 (not {{1}})
  • Must be strings
  • All required variables must be provided

Backward Compatibility:

  • Freeform messages still work (within 24-hour window)
  • Templates are optional (can still send without)
  • Existing code continues to work

🐛 Troubleshooting

Error 63016 Still Occurring:

  • Template not approved yet
  • providerTemplateId not set in database
  • Using wrong Content SID

Template Variables Not Working:

  • Check variable numbering (1, 2, 3)
  • Ensure all variables are strings
  • Verify template structure matches

Message Not Sending:

  • Check API_URL environment variable is set
  • Verify Twilio credentials
  • Confirm template is active

📚 Next Steps

  1. Create Templates in Twilio:

    • Invoice template
    • Payment reminder template
    • Order confirmation template
  2. Update Database:

    • Add provider_template_id to templates
    • Test with real Content SIDs
  3. Test Thoroughly:

    • Send test messages
    • Verify delivery
    • Monitor logs
  4. Production Deployment:

    • Run migration
    • Deploy updated code
    • Monitor performance

🎉 Summary

WhatsApp template support is now fully implemented! You can now send WhatsApp messages at any time without worrying about the 24-hour messaging window restriction.

For detailed setup instructions, see: whatsapp-templates-setup-guide.md


Questions or Issues?

  • Check the troubleshooting section above
  • Review the setup guide
  • Contact the development team