Skip to main content

Social Controller

The Social Controller provides comprehensive social media integration capabilities including account connection, platform management, and social media automation for the VChata platform.

Base Path

/social

Overview

This controller enables complete social media integration:
  • 🔗 Account Connection - Connect and manage social media accounts
  • 📱 Multi-Platform Support - Facebook, Instagram, TikTok, and more
  • 🔄 Token Management - Secure token storage and refresh
  • 📊 Account Analytics - Social media account performance tracking
  • 🛡️ Security - Secure authentication and data protection
  • 🔧 Webhook Integration - Real-time social media event handling

Authentication & Authorization

  • 🔐 All endpoints require valid JWT authentication token
  • 🏢 All operations are scoped to the user’s current organization
  • 👥 Organization membership required for all operations

Account Management

Connect Social Account

POST /social/connect
Authorization: Bearer <token>
Content-Type: application/json

{
  "platform": "FACEBOOK",
  "accessToken": "EAABwzLixnjYBO...",
  "refreshToken": "EAAK...",
  "expiresIn": 3600,
  "platformUserId": "123456789",
  "platformUserName": "Acme Corp Facebook",
  "permissions": ["pages_manage_posts", "pages_read_engagement"]
}
{
  "success": true,
  "socialAccount": {
    "id": "social_123",
    "organizationId": "org_abc123",
    "platform": "FACEBOOK",
    "platformUserId": "123456789",
    "platformUserName": "Acme Corp Facebook",
    "platformUserEmail": "[email protected]",
    "permissions": ["pages_manage_posts", "pages_read_engagement"],
    "isActive": true,
    "lastSyncAt": "2024-01-15T10:30:00Z",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  },
  "message": "Social account connected successfully"
}
Description: Connects a social media account to the organization for automation and management.
body
object

Get Social Accounts

GET /social/accounts?platform=FACEBOOK&isActive=true
Authorization: Bearer <token>
{
  "success": true,
  "socialAccounts": [
    {
      "id": "social_123",
      "organizationId": "org_abc123",
      "platform": "FACEBOOK",
      "platformUserId": "123456789",
      "platformUserName": "Acme Corp Facebook",
      "platformUserEmail": "[email protected]",
      "permissions": ["pages_manage_posts", "pages_read_engagement"],
      "isActive": true,
      "lastSyncAt": "2024-01-15T10:30:00Z",
      "stats": {
        "totalPosts": 25,
        "totalFollowers": 1500,
        "totalEngagement": 850,
        "lastPostDate": "2024-01-20T15:30:00Z"
      },
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    }
  ],
  "total": 1,
  "message": "Social accounts retrieved successfully"
}
Description: Retrieves connected social media accounts with optional filtering.
query
object

Update Social Account

PATCH /social/accounts/social_123
Authorization: Bearer <token>
Content-Type: application/json

{
  "platformUserName": "Updated Acme Corp Facebook",
  "permissions": ["pages_manage_posts", "pages_read_engagement", "pages_show_list"]
}
{
  "success": true,
  "socialAccount": {
    "id": "social_123",
    "platformUserName": "Updated Acme Corp Facebook",
    "permissions": ["pages_manage_posts", "pages_read_engagement", "pages_show_list"],
    "updatedAt": "2024-01-20T16:00:00Z"
  },
  "message": "Social account updated successfully"
}
Description: Updates social media account information and permissions.

Disconnect Social Account

DELETE /social/accounts/social_123
Authorization: Bearer <token>
{
  "success": true,
  "message": "Social account disconnected successfully"
}
Description: Disconnects and removes a social media account from the organization.

Token Management

Refresh Access Token

POST /social/accounts/social_123/refresh-token
Authorization: Bearer <token>
Content-Type: application/json

{
  "refreshToken": "EAAK..."
}
{
  "success": true,
  "tokenInfo": {
    "accessToken": "EAABwzLixnjYBO...",
    "refreshToken": "EAAK...",
    "expiresIn": 3600,
    "tokenType": "bearer",
    "refreshedAt": "2024-01-20T16:00:00Z"
  },
  "message": "Access token refreshed successfully"
}
Description: Refreshes an expired access token using the refresh token.

Validate Token

POST /social/accounts/social_123/validate-token
Authorization: Bearer <token>
{
  "success": true,
  "validation": {
    "isValid": true,
    "expiresAt": "2024-01-21T16:00:00Z",
    "permissions": ["pages_manage_posts", "pages_read_engagement"],
    "platformUserId": "123456789",
    "validatedAt": "2024-01-20T16:00:00Z"
  },
  "message": "Token validated successfully"
}
Description: Validates the current access token and checks its permissions.

Platform Integration

Get Platform Pages

GET /social/accounts/social_123/pages
Authorization: Bearer <token>
{
  "success": true,
  "pages": [
    {
      "id": "page_123",
      "name": "Acme Corporation",
      "category": "Business",
      "platformPageId": "987654321",
      "url": "https://facebook.com/AcmeCorporation",
      "isActive": true,
      "followersCount": 1500,
      "lastPostDate": "2024-01-20T15:30:00Z"
    }
  ],
  "total": 1,
  "message": "Platform pages retrieved successfully"
}
Description: Retrieves pages associated with the connected social account.

Sync Account Data

POST /social/accounts/social_123/sync
Authorization: Bearer <token>
Content-Type: application/json

{
  "syncType": "full",
  "includePosts": true,
  "includeFollowers": true,
  "includeEngagement": true
}
{
  "success": true,
  "syncResult": {
    "syncType": "full",
    "postsSynced": 25,
    "followersSynced": 1500,
    "engagementSynced": 850,
    "syncDuration": 15.2,
    "lastSyncAt": "2024-01-20T16:00:00Z"
  },
  "message": "Account data synced successfully"
}
Description: Synchronizes account data from the social media platform.

Webhook Integration

Setup Webhook

POST /social/accounts/social_123/webhook
Authorization: Bearer <token>
Content-Type: application/json

{
  "webhookUrl": "https://api.vchata.com/webhooks/facebook/social_123",
  "events": ["messages", "comments", "mentions", "posts"],
  "verifyToken": "verify_token_123"
}
{
  "success": true,
  "webhook": {
    "id": "webhook_123",
    "socialAccountId": "social_123",
    "webhookUrl": "https://api.vchata.com/webhooks/facebook/social_123",
    "events": ["messages", "comments", "mentions", "posts"],
    "verifyToken": "verify_token_123",
    "isActive": true,
    "createdAt": "2024-01-20T16:00:00Z"
  },
  "message": "Webhook setup successfully"
}
Description: Sets up webhook for real-time social media events.

Verify Webhook

GET /social/accounts/social_123/webhook/verify?hub.mode=subscribe&hub.challenge=challenge_123&hub.verify_token=verify_token_123
Authorization: Bearer <token>
challenge_123
Description: Verifies webhook setup with the social media platform.

Account Analytics

Get Account Stats

GET /social/accounts/social_123/stats?dateFrom=2024-01-01&dateTo=2024-01-31
Authorization: Bearer <token>
{
  "success": true,
  "stats": {
    "socialAccountId": "social_123",
    "platform": "FACEBOOK",
    "dateRange": {
      "from": "2024-01-01",
      "to": "2024-01-31"
    },
    "overview": {
      "totalPosts": 25,
      "totalFollowers": 1500,
      "totalEngagement": 850,
      "totalReach": 12000,
      "totalClicks": 450
    },
    "engagement": {
      "averageEngagementRate": 7.1,
      "averageClickThroughRate": 3.8,
      "topEngagingPost": {
        "id": "post_123",
        "engagement": 150,
        "reach": 1250
      }
    },
    "growth": {
      "followerGrowth": 125,
      "engagementGrowth": 15.2,
      "reachGrowth": 8.5
    },
    "trends": [
      {
        "date": "2024-01-01",
        "followers": 1475,
        "engagement": 45,
        "reach": 800
      },
      {
        "date": "2024-01-02",
        "followers": 1480,
        "engagement": 52,
        "reach": 850
      }
    ]
  },
  "message": "Account statistics retrieved successfully"
}
Description: Retrieves comprehensive analytics for a social media account.

Platform Types

Supported Platforms

  • FACEBOOK - Facebook Pages and personal profiles
  • INSTAGRAM - Instagram Business and Creator accounts
  • TIKTOK - TikTok Business accounts
  • TWITTER - Twitter/X Business accounts
  • LINKEDIN - LinkedIn Company pages
  • YOUTUBE - YouTube channels

Platform-Specific Features

Error Responses

Common Errors

{
  "success": false,
  "statusCode": 400,
  "message": [
    "platform is required",
    "accessToken must be a valid token",
    "platformUserId is required"
  ],
  "error": "Bad Request"
}
{
  "success": false,
  "statusCode": 401,
  "message": "Invalid or expired access token",
  "error": "Unauthorized"
}
{
  "success": false,
  "statusCode": 403,
  "message": "Insufficient permissions for this operation",
  "error": "Forbidden"
}
{
  "success": false,
  "statusCode": 409,
  "message": "Social account already connected",
  "error": "Conflict"
}
{
  "success": false,
  "statusCode": 502,
  "message": "Social media platform temporarily unavailable",
  "error": "Bad Gateway"
}

Security Features

Token Security

  • Encrypted Storage - All tokens are encrypted at rest
  • Automatic Refresh - Tokens are automatically refreshed before expiration
  • Permission Validation - Regular permission checks and updates
  • Secure Transmission - All API calls use HTTPS encryption

Data Protection

  • Minimal Data Collection - Only necessary data is stored
  • Data Retention - Automatic cleanup of expired data
  • Access Control - Organization-scoped access control
  • Audit Logging - Complete audit trail for all operations

Integration Examples

Complete Account Setup Flow

// Complete social account setup workflow
async function setupSocialAccount(organizationId: string, platformData: any) {
  try {
    // 1. Connect social account
    const socialAccount = await socialService.connectAccount(
      organizationId,
      platformData
    );

    // 2. Validate permissions
    const validation = await socialService.validatePermissions(
      socialAccount.id
    );

    // 3. Sync initial data
    const syncResult = await socialService.syncAccountData(
      socialAccount.id,
      {
        syncType: "full",
        includePosts: true,
        includeFollowers: true
      }
    );

    // 4. Setup webhook for real-time events
    const webhook = await socialService.setupWebhook(socialAccount.id, {
      webhookUrl: `https://api.vchata.com/webhooks/${platformData.platform}/${socialAccount.id}`,
      events: ["messages", "comments", "mentions"]
    });

    return {
      socialAccount,
      validation,
      syncResult,
      webhook,
      success: true
    };
  } catch (error) {
    // Handle setup errors
    throw error;
  }
}

Token Refresh Flow

// Automatic token refresh workflow
async function refreshTokenIfNeeded(socialAccountId: string) {
  try {
    // 1. Check token validity
    const validation = await socialService.validateToken(socialAccountId);
    
    if (!validation.isValid) {
      // 2. Refresh token
      const tokenInfo = await socialService.refreshAccessToken(
        socialAccountId,
        validation.refreshToken
      );
      
      // 3. Update stored token
      await socialService.updateToken(socialAccountId, tokenInfo);
      
      return tokenInfo;
    }
    
    return validation;
  } catch (error) {
    // Handle token refresh errors
    if (error.code === 'REFRESH_TOKEN_EXPIRED') {
      // Re-authenticate the account
      await socialService.markForReauth(socialAccountId);
    }
    throw error;
  }
}

Performance Optimization

Caching Strategy

// Implement caching for account data
const cachedStats = await accountCache.get(`stats:${socialAccountId}`);
if (!cachedStats) {
  const stats = await socialService.getAccountStats(socialAccountId);
  await accountCache.set(`stats:${socialAccountId}`, stats, 1800); // 30 minutes
}

Rate Limiting

// Implement rate limiting for platform APIs
const rateLimiter = new RateLimiter({
  windowMs: 60000, // 1 minute
  max: 60 // 60 requests per minute
});

const syncWithRateLimit = rateLimiter.wrap(socialService.syncAccountData);

Monitoring and Analytics

Integration Metrics

// Track social integration metrics
const integrationMetrics = {
  totalAccounts: await socialService.getTotalAccounts(organizationId),
  activeAccounts: await socialService.getActiveAccounts(organizationId),
  platformDistribution: await socialService.getPlatformDistribution(organizationId),
  averageSyncTime: await socialService.getAverageSyncTime(organizationId),
  tokenRefreshRate: await socialService.getTokenRefreshRate(organizationId)
};

await analyticsService.track('social_integration_metrics', integrationMetrics);

Error Monitoring

// Monitor social integration errors
const errorMetrics = {
  connectionFailures: await socialService.getConnectionFailures(organizationId),
  tokenExpirations: await socialService.getTokenExpirations(organizationId),
  syncFailures: await socialService.getSyncFailures(organizationId),
  webhookFailures: await socialService.getWebhookFailures(organizationId)
};

await analyticsService.track('social_error_metrics', errorMetrics);