@memberjunction/communication-twilio
Twilio provider for the MemberJunction Communication Framework. This provider enables messaging across multiple channels — SMS, WhatsApp Business, and Facebook Messenger — through the Twilio API. The channel is automatically detected based on recipient format.
Architecture
Section titled “Architecture”graph TD
subgraph twilio["@memberjunction/communication-twilio"]
TP["TwilioProvider"]
CFG["Config Module\n(Environment Variables)"]
CRED["TwilioCredentials"]
DETECT["Channel Detection\n(SMS / WhatsApp / Messenger)"]
end
subgraph tw["Twilio Service"]
API["Twilio REST API"]
SMS["SMS / MMS"]
WA["WhatsApp Business"]
FB["Facebook Messenger"]
end
subgraph base["@memberjunction/communication-types"]
BCP["BaseCommunicationProvider"]
end
BCP --> TP
TP --> CFG
TP --> CRED
TP --> DETECT
TP --> API
API --> SMS
API --> WA
API --> FB
style twilio fill:#2d6a9f,stroke:#1a4971,color:#fff
style tw fill:#7c5295,stroke:#563a6b,color:#fff
style base fill:#2d8659,stroke:#1a5c3a,color:#fff
Installation
Section titled “Installation”npm install @memberjunction/communication-twilioConfiguration
Section titled “Configuration”Set the following environment variables:
# RequiredTWILIO_ACCOUNT_SID=your-account-sidTWILIO_AUTH_TOKEN=your-auth-tokenTWILIO_PHONE_NUMBER=+1234567890
# Optional (for additional channels)TWILIO_WHATSAPP_NUMBER=+1234567890TWILIO_FACEBOOK_PAGE_ID=your-page-idChannel Detection
Section titled “Channel Detection”The provider automatically selects the messaging channel based on the recipient format:
flowchart LR
TO["Recipient Address"] --> CHECK{"Prefix?"}
CHECK -->|"whatsapp:+1..."| WA["WhatsApp Channel"]
CHECK -->|"messenger:psid"| FB["Messenger Channel"]
CHECK -->|"+1234567890"| SMS["SMS Channel"]
style TO fill:#2d6a9f,stroke:#1a4971,color:#fff
style WA fill:#2d8659,stroke:#1a5c3a,color:#fff
style FB fill:#7c5295,stroke:#563a6b,color:#fff
style SMS fill:#b8762f,stroke:#8a5722,color:#fff
| Recipient Format | Channel | From Number Config |
|---|---|---|
+1234567890 | SMS | TWILIO_PHONE_NUMBER |
whatsapp:+1234567890 | TWILIO_WHATSAPP_NUMBER | |
messenger:user_psid | Facebook Messenger | TWILIO_FACEBOOK_PAGE_ID |
Supported Operations
Section titled “Supported Operations”| Operation | Supported | Notes |
|---|---|---|
SendSingleMessage | Yes | Auto-detects channel, supports media URLs |
GetMessages | Yes | Filter by from, to, dateSent |
ForwardMessage | Yes | Reconstructs message body with forward prefix |
ReplyToMessage | Yes | Fetches original, sends to original sender |
CreateDraft | No | Messaging services have no draft concept |
| Extended operations | No | No folder, search, or attachment operations |
Sending SMS
Section titled “Sending SMS”import { CommunicationEngine } from '@memberjunction/communication-engine';import { Message } from '@memberjunction/communication-types';
const engine = CommunicationEngine.Instance;await engine.Config(false, contextUser);
const message = new Message();message.To = '+1234567890';message.Body = 'Hello from MemberJunction!';
const result = await engine.SendSingleMessage('Twilio', 'Standard SMS', message);Sending WhatsApp Message
Section titled “Sending WhatsApp Message”const message = new Message();message.To = 'whatsapp:+1234567890';message.Body = 'Hello via WhatsApp!';
const result = await engine.SendSingleMessage('Twilio', 'Standard SMS', message);Sending Facebook Messenger Message
Section titled “Sending Facebook Messenger Message”const message = new Message();message.To = 'messenger:user_psid';message.Body = 'Hello via Messenger!';
const result = await engine.SendSingleMessage('Twilio', 'Standard SMS', message);Sending Media (MMS / WhatsApp)
Section titled “Sending Media (MMS / WhatsApp)”const message = new Message();message.To = '+1234567890';message.Body = 'Check out this image!';message.ContextData = { mediaUrls: ['https://example.com/image.jpg']};
const result = await engine.SendSingleMessage('Twilio', 'Standard SMS', message);Retrieving Messages
Section titled “Retrieving Messages”const provider = engine.GetProvider('Twilio');
const result = await provider.GetMessages({ NumMessages: 50, ContextData: { from: '+1234567890', to: '+0987654321', dateSent: new Date('2025-01-01') }});
result.Messages.forEach(msg => { console.log(`${msg.From} -> ${msg.To}: ${msg.Body}`);});Per-Request Credentials
Section titled “Per-Request Credentials”import { TwilioCredentials } from '@memberjunction/communication-twilio';
const result = await provider.SendSingleMessage(processedMessage, { accountSid: 'customer-sid', authToken: 'customer-token', phoneNumber: '+1987654321'} as TwilioCredentials);Replying to a Message
Section titled “Replying to a Message”const result = await provider.ReplyToMessage({ MessageID: 'original-twilio-message-sid', Message: processedReply});Forwarding a Message
Section titled “Forwarding a Message”const result = await provider.ForwardMessage({ MessageID: 'message-sid-to-forward', ToRecipients: ['+1234567890', 'whatsapp:+0987654321'], Message: 'FYI - forwarding this message'});TwilioCredentials
Section titled “TwilioCredentials”interface TwilioCredentials extends ProviderCredentialsBase { accountSid?: string; authToken?: string; phoneNumber?: string; whatsappNumber?: string; facebookPageId?: string; disableEnvironmentFallback?: boolean;}Client Caching
Section titled “Client Caching”The provider caches Twilio client instances for performance. Environment credential clients are shared across all calls; per-request credential clients are cached by accountSid.
Important Notes
Section titled “Important Notes”- SMS/messaging channels use plain text only — HTML content is not supported
- Message threading is simulated using Twilio Message SIDs (Twilio has no native thread concept)
- Forwarding reconstructs the message content with a “Forwarded message” prefix
- Media attachments are supported through the
mediaUrlscontext data property - All operations are asynchronous via the Twilio REST API
Dependencies
Section titled “Dependencies”| Package | Purpose |
|---|---|
@memberjunction/communication-types | Base provider class and type definitions |
@memberjunction/core | Logging utilities (LogError, LogStatus) |
@memberjunction/global | RegisterClass decorator |
twilio | Official Twilio SDK |
dotenv | Environment variable loading |
env-var | Environment variable validation |
Development
Section titled “Development”npm run build # Compile TypeScriptnpm run clean # Remove dist directory