Twilio Account Provider
🎯 Overview
The Account Provider (Providers/account.js) retrieves Twilio account information including status, authentication tokens, and account details.
Source: external/Integrations/Twilio/Providers/account.js
Key Capabilities:
- Fetch account details by SID
- Update DashClicks account with Twilio account status
- Sync authentication tokens
🔌 Provider Functions
get()
Fetch Twilio account details and sync with DashClicks account.
Signature:
const get = async(id);
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | String | ✅ | Twilio Account SID (AC...) or Subaccount SID |
Returns:
Promise<{
sid: string; // Account SID
friendlyName: string; // Account display name
status: string; // "active", "suspended", "closed"
type: string; // "Full", "Trial"
authToken: string; // Auth token for API access
dateCreated: Date;
dateUpdated: Date;
ownerAccountSid: string; // Master account SID (for subaccounts)
uri: string;
}>;
Business Logic:
-
Create Master Twilio Client
- Uses
TWILIO_ACCOUNT_SIDandTWILIO_AUTH_TOKENfrom environment - Required to fetch subaccount details
- Uses
-
Fetch Account by SID
- Calls
client.api.v2010.accounts(id).fetch() - Works for both master account and subaccounts
- Calls
-
Update DashClicks Account
- Finds account in MongoDB by
twilio_account.sid - Updates
twilio_account.authTokenandtwilio_account.status - Syncs Twilio account state with DashClicks database
- Finds account in MongoDB by
-
Return Account Details
Example Usage:
const accountProvider = require('./Providers/account');
// Get master account details
const masterAccount = await accountProvider.get(process.env.TWILIO_ACCOUNT_SID);
console.log('Account:', masterAccount.friendlyName);
console.log('Status:', masterAccount.status); // active, suspended, closed
console.log('Type:', masterAccount.type); // Full or Trial
console.log('Auth Token:', masterAccount.authToken);
// Output:
// Account: DashClicks Master
// Status: active
// Type: Full
// Auth Token: ********************************
Get Subaccount Details:
// Fetch subaccount information
const subaccount = await accountProvider.get('AC1234567890abcdef1234567890abcdef');
console.log('Subaccount:', subaccount.friendlyName);
console.log('Owner:', subaccount.ownerAccountSid); // Master account SID
console.log('Status:', subaccount.status);
Data Flow:
sequenceDiagram
participant API as DashClicks API
participant Provider as Account Provider
participant Twilio as Twilio SDK
participant DB as MongoDB
API->>Provider: get(accountSID)
Provider->>Twilio: accounts(accountSID).fetch()
Twilio-->>Provider: Account details
Provider->>DB: Account.findOneAndUpdate()
Note over DB: Update twilio_account.authToken<br/>Update twilio_account.status
Provider-->>API: Return account details
style Provider fill:#e3f2fd
style Twilio fill:#fff4e6
💡 Integration Examples
Account Health Check
async function checkTwilioAccountHealth(accountSID) {
try {
const account = await accountProvider.get(accountSID);
const health = {
sid: account.sid,
name: account.friendlyName,
status: account.status,
type: account.type,
isActive: account.status === 'active',
isTrial: account.type === 'Trial',
lastChecked: new Date(),
};
// Alert if suspended
if (account.status === 'suspended') {
console.error('⚠️ Twilio account suspended:', account.sid);
await sendAlert('Twilio account suspended', account);
}
return health;
} catch (error) {
console.error('Failed to check Twilio account:', error);
return { isActive: false, error: error.message };
}
}
Sync All Subaccounts
async function syncAllTwilioAccounts() {
// Get all DashClicks accounts with Twilio integration
const accounts = await Account.find({
'twilio_account.sid': { $exists: true },
});
const synced = [];
const failed = [];
for (const account of accounts) {
try {
const twilioAccount = await accountProvider.get(account.twilio_account.sid);
synced.push({
accountId: account._id,
twilioSid: twilioAccount.sid,
status: twilioAccount.status,
});
} catch (error) {
failed.push({
accountId: account._id,
twilioSid: account.twilio_account.sid,
error: error.message,
});
}
}
return { synced, failed };
}
Account Status Dashboard
async function getTwilioAccountsDashboard() {
const accounts = await Account.find({
'twilio_account.sid': { $exists: true },
}).lean();
const dashboard = {
total: accounts.length,
active: 0,
suspended: 0,
closed: 0,
trial: 0,
full: 0,
accounts: [],
};
for (const account of accounts) {
try {
const twilioAccount = await accountProvider.get(account.twilio_account.sid);
// Count by status
dashboard[twilioAccount.status.toLowerCase()]++;
// Count by type
if (twilioAccount.type === 'Trial') {
dashboard.trial++;
} else {
dashboard.full++;
}
dashboard.accounts.push({
dashClicksAccountId: account._id,
twilioSid: twilioAccount.sid,
name: twilioAccount.friendlyName,
status: twilioAccount.status,
type: twilioAccount.type,
});
} catch (error) {
console.error(`Failed to fetch ${account.twilio_account.sid}:`, error);
}
}
return dashboard;
}
🚨 Error Handling
Common Errors
1. Account Not Found
Error: 20404 - The requested resource was not found
- Cause: Invalid Account SID
- Solution: Verify Account SID is correct
2. Authentication Failed
Error: 20003 - Authenticate;
- Cause: Invalid master account credentials in environment
- Solution: Verify
TWILIO_ACCOUNT_SIDandTWILIO_AUTH_TOKEN
3. Access Denied
Error: 20403 - Forbidden;
- Cause: Attempting to access account without permission
- Solution: Ensure using master account credentials for subaccounts
⚡ Performance Considerations
- Caching: Account details rarely change, consider caching for 1-5 minutes
- Database Sync: Updates DashClicks database on every call
- Master Credentials: Always uses master account credentials (not multi-tenant)
🔗 Related Documentation
- Twilio Integration Overview - Main Twilio integration
- Subaccounts Provider - Subaccount management
- Pricing Provider - Account balance and pricing
External Resources: