ConnectGain Complete API Documentation¶
Version: 3.0.0
Last Updated: January 2025
Base URL: https://txpaxbxhnvnhsjwwaeoy.supabase.co
Table of Contents¶
- Overview
- Authentication
- Edge Functions API
- REST API Reference
- Features & Capabilities
- Error Handling
- Rate Limits & Best Practices
Overview¶
ConnectGain is a comprehensive customer engagement and CRM platform that provides:
- Multi-channel messaging (WhatsApp, Messenger, Instagram, Telegram, TikTok)
- CRM functionality (Contacts, Deals, Companies, Pipelines)
- Conversation management (Inbox, Messages, Assignments)
- Automation (Bot Flows, Automation Rules, Templates)
- Campaign management (Broadcast campaigns, SMS, WhatsApp)
- Project management (Projects, Tasks, Milestones)
- Analytics & Reporting (Dashboard widgets, Performance metrics)
- Team collaboration (Organizations, Users, Permissions, Invitations)
- Webhooks (Event-driven integrations)
- API integrations (External system integration via API keys)
API Types¶
ConnectGain provides three types of APIs:
- Supabase Edge Functions - Custom serverless functions for business logic
- Supabase REST API - Direct database access via PostgREST
- External APIs - APIs designed for external systems (using API keys)
Authentication¶
Standard Authentication (Bearer Token)¶
Most APIs use Bearer token authentication with your Supabase anon key:
Getting your anon key:
1. Go to Supabase Dashboard
2. Navigate to Settings → API
3. Copy the anon public key
API Key Authentication (External Systems)¶
External APIs use X-API-Key header for authentication:
API keys are generated per organization and can be created via the Generate API Key endpoint.
Key Features:
- Prefixed with cg_ for easy identification
- Scoped to the organization that created it
- Can have custom permissions (send messages, read messages, etc.)
- Can have expiration dates
- Should be stored securely (only shown once on creation)
Edge Functions API¶
Edge Functions are serverless functions that handle business logic, integrations, and complex operations.
Message Sending Functions¶
WhatsApp Lite - Send Message¶
Send messages via WhatsApp Lite (AppGain integration).
Endpoint: POST /functions/v1/whatsapp-lite-send
Headers:
Request Body:
{
"to": "201001383533",
"message": "Hello from ConnectGain!",
"suitId": "YOUR_SUIT_ID",
"organizationId": "org-uuid",
"contactName": "John Doe",
"from": "AIBot",
"conversationId": "conv-uuid"
}
Parameters:
- to (required): Phone number in international format (e.g., "201001383533")
- message (required): Message content (max 4096 characters)
- suitId (optional): AppGain Suit ID (required if organizationId not provided)
- organizationId (optional): Organization UUID (required if suitId not provided)
- contactName (optional): Contact name for display
- from (optional): Sender name for UI display
- conversationId (optional): Existing conversation ID
Response:
{
"success": true,
"result": {
"messageId": "message_id",
"id": "message_id"
},
"conversationId": "conv-uuid",
"contactId": "contact-uuid"
}
Curl Example:
curl -X POST https://txpaxbxhnvnhsjwwaeoy.supabase.co/functions/v1/whatsapp-lite-send \
-H "Authorization: Bearer YOUR_ANON_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": "201001383533",
"message": "Hello!",
"suitId": "YOUR_SUIT_ID",
"from": "AIBot"
}'
WhatsApp Cloud - Send Message¶
Send messages via WhatsApp Cloud API (Meta).
Endpoint: POST /functions/v1/whatsapp-cloud-send
Request Body:
{
"to": "phone_number",
"message": "Hello via WhatsApp Cloud!",
"conversationId": "conv-uuid",
"accessToken": "facebook_access_token",
"phoneNumberId": "phone_number_id"
}
Facebook Messenger - Send Message¶
Send messages via Facebook Messenger.
Endpoint: POST /functions/v1/messenger-send
Request Body:
{
"to": "user_psid",
"message": "Hello via Messenger!",
"conversationId": "conv-uuid",
"accessToken": "messenger_access_token"
}
Instagram - Send Message¶
Send direct messages via Instagram.
Endpoint: POST /functions/v1/instagram-send
Request Body:
Telegram - Send Message¶
Send messages via Telegram.
Endpoint: POST /functions/v1/telegram-send
Request Body:
TikTok - Send Message¶
Send messages via TikTok.
Endpoint: POST /functions/v1/tiktok-send
Request Body:
Search & Import Functions¶
Search Contacts¶
Advanced contact search with filtering by name, phone, email, tags, and company.
Endpoint: POST /functions/v1/search-contacts
Headers:
Request Body:
Parameters:
- searchTerm (optional): Search term for name, phone, email, or tags
- tags (optional): Array of tags to filter by
- dealStatus (optional): Filter by deal status ("open", "closed", etc.)
Response:
{
"contacts": [
{
"id": "uuid",
"first_name": "John",
"last_name": "Doe",
"phones": ["+1234567890"],
"emails": ["john@example.com"],
"tags": ["customer"],
"company": {
"id": "uuid",
"name": "Acme Inc"
},
"assignee": {
"id": "uuid",
"first_name": "Agent",
"last_name": "Name"
}
}
],
"count": 1
}
Features: - Searches across first name, last name, full name, reversed name - Phone number matching (with country code variations) - Email matching (full email or username part) - Tag matching - Company name matching - Returns up to 2000 results - Includes related company and assignee data
Search Companies¶
Search companies by name, domain, email, phone, city, industry, or description.
Endpoint: POST /functions/v1/search-companies
Request Body:
Parameters:
- searchTerm (optional): Search term for company fields
- country (optional): Filter by country (use __no_country__ for null countries)
Response:
{
"companies": [
{
"id": "uuid",
"name": "Acme Inc",
"domain": "acme.com",
"email": "contact@acme.com",
"phone": "+1234567890",
"city": "New York",
"country": "US",
"industry": "Technology"
}
]
}
Import Contacts (CSV)¶
Bulk import contacts from CSV data.
Endpoint: POST /functions/v1/import-contacts
Request Body:
{
"csvData": "First Name,Last Name,Email,Phone Number\nJohn,Doe,john@example.com,+1234567890",
"organizationId": "org-uuid"
}
Supported CSV Fields: - First Name, Last Name - Email, Phone Number, Mobile Phone Number - Company name, Job Title - Lead Status, Lifecycle Stage - Street Address, City, State/Region, Postal Code, Country/Region
Response:
Import Companies (CSV)¶
Bulk import companies from CSV data.
Endpoint: POST /functions/v1/import-companies
Request Body:
{
"csvData": "Company name,Company Domain Name,Phone Number,City,Country/Region\nAcme Inc,acme.com,+1234567890,New York,US",
"organizationId": "org-uuid"
}
Supported CSV Fields: - Company name, Company Domain Name, Website URL - Industry, Phone Number - City, State/Region, Country/Region, Street Address, Postal Code - Annual Revenue, Number of Employees - LinkedIn Company Page, Facebook Company Page, Twitter Handle - Logo URL, Description - Lifecycle Stage, Lead Status, Company owner
Import Kommo Leads¶
Import leads from Kommo CRM.
Endpoint: POST /functions/v1/import-kommo-leads
Request Body:
External APIs¶
Insert Message (External)¶
Insert a message into ConnectGain from an external system. Automatically creates or finds contacts and conversations.
Endpoint: POST /functions/v1/insert-message
Headers:
Request Body:
{
"phone": "201001383533",
"content": "Hello from external system!",
"direction": "outgoing",
"status": "sent",
"message_type": "text",
"metadata": {},
"channel_account_id": "channel-uuid"
}
Parameters:
- phone (required): Phone number in international format
- content (required): Message content/text
- direction (required): "incoming" or "outgoing"
- status (required): "sent", "received", "delivered", "failed", etc.
- message_type (optional): Message type (default: "text")
- metadata (optional): Additional metadata object
- channel_account_id (optional): Specific channel account ID
Response:
{
"success": true,
"message": {
"id": "message-uuid",
"conversation_id": "conversation-uuid",
"contact_id": "contact-uuid"
}
}
Behavior: - Finds or creates contact based on phone number - Finds or creates conversation for the contact - Reopens closed conversations if message is inbound - Inserts message with specified direction and status - Updates conversation's last_message_at timestamp
Curl Example:
curl -X POST \
'https://txpaxbxhnvnhsjwwaeoy.supabase.co/functions/v1/insert-message' \
-H 'X-API-Key: cg_abc123def456...' \
-H 'Content-Type: application/json' \
-d '{
"phone": "201001383533",
"content": "Hello from external system!",
"direction": "outgoing",
"status": "sent"
}'
Generate API Key¶
Create a new API key for external system integration.
Endpoint: POST /functions/v1/generate-api-key
Headers:
Request Body:
{
"name": "External System Integration",
"expires_in_days": 365,
"permissions": {
"can_send_messages": true,
"can_read_messages": false
}
}
Parameters:
- name (required): Descriptive name for the API key
- expires_in_days (optional): Number of days until expiration (null for no expiration)
- permissions (optional): Permission object
- can_send_messages (boolean): Allow sending messages
- can_read_messages (boolean): Allow reading messages
Response:
{
"success": true,
"api_key": "cg_abc123def456...",
"key_info": {
"id": "key-uuid",
"name": "External System Integration",
"key_prefix": "cg_abc123...",
"expires_at": "2026-01-15T10:30:00Z",
"created_at": "2025-01-15T10:30:00Z"
},
"warning": "Save this API key now. You will not be able to see it again!"
}
Important: The full API key is only shown once. Store it securely immediately after creation.
Organization & Authentication Functions¶
List Organizations¶
Get all organizations the authenticated user has access to.
Endpoint: GET /functions/v1/list-organizations
Headers:
Response:
{
"organizations": [
{
"id": "uuid",
"name": "Organization Name",
"suitId": "YOUR_SUIT_ID",
"hasAppgainCredentials": true
}
],
"count": 1
}
Switch Organization¶
Switch the user's active organization.
Endpoint: POST /functions/v1/switch-organization
Request Body:
Accept Invitation¶
Accept a team invitation and create user account.
Endpoint: POST /functions/v1/accept-invitation
Request Body:
{
"token": "invitation_token",
"email": "user@example.com",
"password": "secure_password",
"first_name": "John",
"last_name": "Doe"
}
Send Invitation Email¶
Send an invitation email to a new team member.
Endpoint: POST /functions/v1/send-invitation-email
Request Body:
Facebook OAuth¶
Handle Facebook OAuth callback for channel integration.
Endpoint: GET /functions/v1/facebook-oauth?code=oauth_code
Payment & Subscription Functions¶
Create Stripe Checkout¶
Create a Stripe checkout session for subscription.
Endpoint: POST /functions/v1/create-checkout
Request Body:
Response:
Get Customer Portal URL¶
Get Stripe customer portal URL for managing subscription.
Endpoint: GET /functions/v1/customer-portal
Response:
Check Subscription¶
Check current subscription status.
Endpoint: GET /functions/v1/check-subscription
Response:
Webhook Functions¶
Webhook endpoints receive events from external services (WhatsApp, Messenger, Instagram, Telegram, TikTok, Stripe).
Available Webhooks:
- POST /functions/v1/whatsapp-lite-webhook - WhatsApp Lite webhooks
- POST /functions/v1/whatsapp-cloud-webhook - WhatsApp Cloud webhooks
- POST /functions/v1/messenger-webhook - Facebook Messenger webhooks
- POST /functions/v1/instagram-webhook - Instagram webhooks
- POST /functions/v1/telegram-webhook - Telegram webhooks
- POST /functions/v1/tiktok-webhook - TikTok webhooks
- POST /functions/v1/appgain-whatsapp-webhook - AppGain WhatsApp webhooks
- POST /functions/v1/stripe-webhook - Stripe payment webhooks
These endpoints are typically configured in the external service's webhook settings and handle incoming events automatically.
REST API Reference¶
The REST API provides direct access to all database tables via PostgREST. All endpoints support standard HTTP methods (GET, POST, PATCH, DELETE) and PostgREST query syntax.
Base URL¶
Common Headers¶
apikey: YOUR_ANON_KEY
Authorization: Bearer YOUR_ANON_KEY
Content-Type: application/json
Prefer: return=representation # Optional: return created/updated record
Query Parameters¶
PostgREST supports powerful query parameters:
select- Select specific columns or relations (e.g.,select=*,contacts(*))filter- Filter rows (e.g.,id=eq.uuid,status=eq.OPEN)order- Order results (e.g.,order=created_at.desc)limit- Limit results (e.g.,limit=100)offset- Pagination offset (e.g.,offset=50)
Filter Operators:
- eq - Equal
- neq - Not equal
- gt - Greater than
- gte - Greater than or equal
- lt - Less than
- lte - Less than or equal
- like - Pattern match (case-sensitive)
- ilike - Pattern match (case-insensitive)
- is - IS NULL / IS NOT NULL
- in - In array
- contains - JSONB contains
Contacts API¶
Base Endpoint: /rest/v1/contacts
List Contacts:
Get Single Contact:
Create Contact:
POST /rest/v1/contacts
Content-Type: application/json
{
"organization_id": "org-uuid",
"first_name": "John",
"last_name": "Doe",
"phones": ["+1234567890"],
"emails": ["john@example.com"],
"tags": ["customer", "vip"],
"custom_fields": {
"company": "Acme Inc",
"position": "Manager"
},
"opt_in_status": true
}
Update Contact:
PATCH /rest/v1/contacts?id=eq.{contact_id}
Content-Type: application/json
{
"first_name": "Jane",
"tags": ["customer", "vip", "priority"]
}
Delete Contact:
Search Contacts:
Contact Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- first_name (text) - First name
- last_name (text) - Last name
- phones (text[]) - Array of phone numbers
- emails (text[]) - Array of email addresses
- tags (text[]) - Array of tags
- custom_fields (jsonb) - Custom field data
- opt_in_status (boolean) - Marketing opt-in status
- company_id (UUID) - Associated company
- assignee_id (UUID) - Assigned user
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Companies API¶
Base Endpoint: /rest/v1/companies
List Companies:
Create Company:
POST /rest/v1/companies
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "Acme Inc",
"domain": "acme.com",
"email": "contact@acme.com",
"phone": "+1234567890",
"city": "New York",
"country": "US",
"industry": "Technology",
"description": "Company description"
}
Company Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Company name
- domain (text) - Company domain
- email (text) - Contact email
- phone (text) - Contact phone
- city (text) - City
- country (text) - Country code
- industry (text) - Industry
- description (text) - Company description
- employee_count (integer) - Number of employees
- annual_revenue (numeric) - Annual revenue
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Deals API¶
Base Endpoint: /rest/v1/deals
List Deals:
GET /rest/v1/deals?select=*,contacts(*),profiles!deals_owner_id_fkey(*)&organization_id=eq.{org_id}&order=created_at.desc
Create Deal:
POST /rest/v1/deals
Content-Type: application/json
{
"organization_id": "org-uuid",
"contact_id": "contact-uuid",
"pipeline_id": "pipeline-uuid",
"title": "New Lead - John Doe",
"stage": "lead",
"value": 5000,
"probability": 10,
"expected_close_date": "2025-02-15",
"custom_fields": {
"source": "website",
"priority": "high"
}
}
Update Deal Stage:
PATCH /rest/v1/deals?id=eq.{deal_id}
Content-Type: application/json
{
"stage": "qualified",
"probability": 50,
"value": 7500
}
Deal Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- contact_id (UUID) - Associated contact
- pipeline_id (UUID) - Associated pipeline
- owner_id (UUID) - Deal owner
- title (text) - Deal title
- stage (text) - Current stage (lead, qualified, proposal, negotiation, closed_won, closed_lost)
- value (numeric) - Deal value
- probability (integer) - Win probability (0-100)
- expected_close_date (date) - Expected close date
- tags (text[]) - Array of tags
- custom_fields (jsonb) - Custom field data
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Pipelines API¶
Base Endpoint: /rest/v1/pipelines
List Pipelines:
Create Pipeline:
POST /rest/v1/pipelines
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "Sales Pipeline",
"stages": "[{\"id\":\"lead\",\"name\":\"Lead\"},{\"id\":\"qualified\",\"name\":\"Qualified\"}]",
"is_default": false
}
Pipeline Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Pipeline name
- stages (jsonb) - Pipeline stages configuration
- is_default (boolean) - Default pipeline flag
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Conversations API¶
Base Endpoint: /rest/v1/conversations
List Conversations:
GET /rest/v1/conversations?select=*,contacts(*),channel_accounts(*),profiles!conversations_assignee_id_fkey(*)&organization_id=eq.{org_id}&order=last_message_at.desc
Create Conversation:
POST /rest/v1/conversations
Content-Type: application/json
{
"organization_id": "org-uuid",
"contact_id": "contact-uuid",
"channel_account_id": "channel-uuid",
"status": "OPEN",
"tags": ["urgent", "customer"]
}
Assign Conversation:
PATCH /rest/v1/conversations?id=eq.{conversation_id}
Content-Type: application/json
{
"assignee_id": "user-uuid"
}
Conversation Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- contact_id (UUID) - Associated contact
- channel_account_id (UUID) - Associated channel
- assignee_id (UUID) - Assigned user
- status (text) - Status (OPEN, CLOSED)
- tags (text[]) - Array of tags
- last_message_at (timestamp) - Last message timestamp
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Messages API¶
Base Endpoint: /rest/v1/messages
List Messages:
Create Message:
POST /rest/v1/messages
Content-Type: application/json
{
"organization_id": "org-uuid",
"conversation_id": "conversation-uuid",
"contact_id": "contact-uuid",
"direction": "OUTBOUND",
"content": "Hello! This is a test message.",
"status": "SENT",
"message_type": "text",
"metadata": {
"sender_name": "AIBot"
}
}
Message Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- conversation_id (UUID) - Associated conversation
- contact_id (UUID) - Associated contact
- sender_id (UUID) - Sender user (null for system messages)
- direction (enum) - INBOUND or OUTBOUND
- content (text) - Message content
- status (enum) - SENT, DELIVERED, READ, FAILED
- message_type (text) - Message type (text, image, video, etc.)
- metadata (jsonb) - Additional metadata
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Tasks API¶
Base Endpoint: /rest/v1/tasks
List Tasks:
Create Task:
POST /rest/v1/tasks
Content-Type: application/json
{
"organization_id": "org-uuid",
"contact_id": "contact-uuid",
"title": "Follow up with customer",
"description": "Call to discuss pricing",
"due_date": "2025-01-30T12:00:00Z",
"completed": false,
"priority": "HIGH"
}
Task Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- contact_id (UUID) - Associated contact
- deal_id (UUID) - Associated deal
- assignee_id (UUID) - Assigned user
- title (text) - Task title
- description (text) - Task description
- due_date (timestamp) - Due date
- completed (boolean) - Completion status
- priority (text) - Priority (LOW, MEDIUM, HIGH)
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Templates API¶
Base Endpoint: /rest/v1/templates
List Templates:
Create Template:
POST /rest/v1/templates
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "Welcome Message",
"components": [{
"type": "BODY",
"text": "Hello {{name}}, welcome to our service!"
}],
"status": "APPROVED",
"category": "UTILITY"
}
Template Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Template name
- components (jsonb) - Template components (WhatsApp template format)
- status (text) - Status (DRAFT, APPROVED, REJECTED)
- category (text) - Category (GENERAL, QUICK_REPLY, UTILITY, MARKETING)
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Bot Flows API¶
Base Endpoint: /rest/v1/bot_flows
List Bot Flows:
Create Bot Flow:
POST /rest/v1/bot_flows
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "Customer Support Flow",
"description": "Automated customer support bot",
"nodes": [],
"edges": [],
"status": "DRAFT",
"version": 1
}
Bot Flow Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Flow name
- description (text) - Flow description
- nodes (jsonb) - Flow nodes configuration
- edges (jsonb) - Flow edges configuration
- status (enum) - DRAFT, PUBLISHED, ARCHIVED
- version (integer) - Flow version
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Automation Rules API¶
Base Endpoint: /rest/v1/automation_rules
List Automation Rules:
Create Automation Rule:
POST /rest/v1/automation_rules
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "Auto Assign New Messages",
"trigger_type": "MESSAGE_CREATED",
"conditions": [{
"field": "direction",
"operator": "equals",
"value": "INBOUND"
}],
"actions": [{
"type": "ASSIGN_CONVERSATION",
"assignee_id": "user-uuid"
}],
"is_active": true
}
Automation Rule Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Rule name
- trigger_type (enum) - Trigger type (MESSAGE_CREATED, DEAL_STAGE_CHANGED, TASK_DUE, CONTACT_CREATED, etc.)
- conditions (jsonb) - Condition array
- actions (jsonb) - Action array
- is_active (boolean) - Active status
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Campaigns API¶
Base Endpoint: /rest/v1/campaigns
List Campaigns:
Create Campaign:
POST /rest/v1/campaigns
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "New Product Launch",
"type": "SMS",
"content": "Check out our new product!",
"target_type": "ALL",
"status": "DRAFT",
"scheduled_at": "2025-02-01T10:00:00Z"
}
Campaign Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Campaign name
- type (enum) - SMS, WHATSAPP_LITE, WHATSAPP_BUSINESS
- content (text) - Campaign content
- target_type (enum) - ALL, TAGS, INDIVIDUAL
- target_tags (text[]) - Target tags (if target_type is TAGS)
- target_contacts (uuid[]) - Target contact IDs (if target_type is INDIVIDUAL)
- status (enum) - DRAFT, SCHEDULED, SENDING, COMPLETED, CANCELLED
- scheduled_at (timestamp) - Scheduled send time
- timezone (text) - Timezone for scheduling
- image_url (text) - Campaign image URL
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Notes API¶
Base Endpoint: /rest/v1/notes
List Notes:
Create Note:
POST /rest/v1/notes
Content-Type: application/json
{
"organization_id": "org-uuid",
"contact_id": "contact-uuid",
"content": "Customer called to inquire about pricing",
"author_id": "user-uuid"
}
Note Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- contact_id (UUID) - Associated contact
- author_id (UUID) - Note author
- content (text) - Note content
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Channel Accounts API¶
Base Endpoint: /rest/v1/channel_accounts
List Channel Accounts:
Create Channel Account:
POST /rest/v1/channel_accounts
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "WhatsApp Business",
"type": "WHATSAPP_CLOUD",
"is_active": true,
"settings": {
"access_token": "token",
"phone_number_id": "phone_id"
}
}
Channel Account Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Channel name
- type (enum) - WHATSAPP_LITE, WHATSAPP_CLOUD, FB_MESSENGER, INSTAGRAM, TELEGRAM, TIKTOK, EMAIL, SMS, SHRINKIT_PUSH
- is_active (boolean) - Active status
- settings (jsonb) - Channel-specific settings
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Projects API¶
Base Endpoint: /rest/v1/projects
List Projects:
Create Project:
POST /rest/v1/projects
Content-Type: application/json
{
"organization_id": "org-uuid",
"name": "New Project",
"description": "Project description",
"status": "PLANNING",
"start_date": "2025-02-01",
"end_date": "2025-03-01"
}
Project Fields:
- id (UUID) - Unique identifier
- organization_id (UUID) - Organization reference
- name (text) - Project name
- description (text) - Project description
- status (enum) - PLANNING, IN_PROGRESS, COMPLETED, DELAYED, CANCELLED
- start_date (date) - Start date
- end_date (date) - End date
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Organizations & Users API¶
Base Endpoint: /rest/v1/organizations and /rest/v1/profiles
List Organizations:
List Profiles (Users):
Update Profile:
PATCH /rest/v1/profiles?id=eq.{user_id}
Content-Type: application/json
{
"first_name": "John",
"last_name": "Doe",
"role": "ADMIN"
}
Profile Fields:
- id (UUID) - User UUID (references auth.users)
- organization_id (UUID) - Organization reference
- role (enum) - OWNER, ADMIN, AGENT
- first_name (text) - First name
- last_name (text) - Last name
- email (text) - Email address
- avatar_url (text) - Avatar URL
- is_active (boolean) - Active status
- created_at (timestamp) - Creation timestamp
- updated_at (timestamp) - Last update timestamp
Features & Capabilities¶
Dashboard & Analytics¶
Dashboard Features: - Customizable widgets (drag-and-drop) - Real-time metrics (messages, conversations, deals, tasks) - Performance charts - Date range filtering - Widget configuration and visibility controls
Analytics Features: - Average response time - SLA compliance tracking - Total messages count - Resolved conversations - Unassigned messages - Overdue conversations - Contact and deal metrics - Task completion rates
Contact Management¶
Features: - Contact CRUD operations - Bulk import (CSV) - Advanced search (name, phone, email, tags, company) - Tag management - Custom fields support - Company association - Contact assignment - Duplicate detection and merging - Contact notes - Deal association - Task association
Views: - Grid view (cards) - Table view - Contact details dialog - Contact edit dialog
Company Management¶
Features: - Company CRUD operations - Bulk import (CSV) - Search by name, domain, email, phone, city, industry - Country filtering - Company details view - Contact association - Deal association
Views: - Grid view (cards) - Table view - Company details dialog
Deal Pipeline Management¶
Features: - Deal CRUD operations - Pipeline management (multiple pipelines) - Stage management (drag-and-drop) - Deal filtering (stage, value range, assignee, tags) - Deal assignment - Value and probability tracking - Expected close date - Custom fields - Deal notes - Contact association
Views: - Kanban board view - Deal details dialog - Pipeline configuration
Conversation Management¶
Features: - Conversation CRUD operations - Message threading - Conversation assignment - Status management (OPEN, CLOSED) - Tag management - Real-time updates - Multi-channel support - Contact association - Deal creation from conversation
Views: - Conversation list - Message thread view - Contact panel - Mobile-responsive design
Message Management¶
Features: - Message CRUD operations - Multi-channel messaging - Message status tracking (SENT, DELIVERED, READ, FAILED) - Message types (text, image, video, audio, document) - Metadata support - Real-time delivery - Message history
Task Management¶
Features: - Task CRUD operations - Task assignment - Due date tracking - Priority levels (LOW, MEDIUM, HIGH) - Completion tracking - Task filtering (status, priority, assignee) - Contact and deal association - Calendar view - List view
Views: - List view - Calendar view - Task details dialog
Template Management¶
Features: - Template CRUD operations - WhatsApp template format support - Template categories (GENERAL, QUICK_REPLY, UTILITY, MARKETING) - Template status (DRAFT, APPROVED, REJECTED) - Template components (BODY, HEADER, FOOTER, BUTTONS) - Variable support ({{name}}, {{company}}, etc.)
Bot Flows¶
Features: - Bot flow CRUD operations - Visual flow builder - Node-based flow design - Flow publishing (DRAFT, PUBLISHED, ARCHIVED) - Version management - Flow execution tracking - Bot session management
Flow Node Types: - Send Message - Collect Input - Condition - Webhook - Assign Conversation - Create Task - End Flow
Automation Rules¶
Features: - Automation rule CRUD operations - Trigger-based automation - Condition matching - Action execution - Active/inactive toggle
Trigger Types:
- message.received - New message received
- message.sent - Message sent
- contact.created - Contact created
- contact.updated - Contact updated
- contact.assigned - Contact assigned
- deal.created - Deal created
- deal.updated - Deal updated
- deal.stage.changed - Deal stage changed
- deal.assigned - Deal assigned
- conversation.created - Conversation created
- conversation.assigned - Conversation assigned
- conversation.status.changed - Conversation status changed
Action Types:
- SEND_MESSAGE - Send a message
- ASSIGN_CONVERSATION - Assign conversation to user
- ASSIGN_CONTACT - Assign contact to user
- ASSIGN_DEAL - Assign deal to user
- CREATE_TASK - Create a task
- CREATE_DEAL - Create a deal
- ADD_TAG - Add tag to contact/deal
- REMOVE_TAG - Remove tag from contact/deal
- UPDATE_FIELD - Update custom field
Campaign Management¶
Features: - Campaign CRUD operations - Campaign types (SMS, WHATSAPP_LITE, WHATSAPP_BUSINESS) - Target selection (ALL, TAGS, INDIVIDUAL) - Campaign scheduling - Timezone support - Image support - Campaign status tracking (DRAFT, SCHEDULED, SENDING, COMPLETED, CANCELLED) - Campaign preview - Notification logs
Views: - Campaign list - Campaign creation dialog - Campaign preview - Notification logs
Project Management¶
Features: - Project CRUD operations - Project status tracking (PLANNING, IN_PROGRESS, COMPLETED, DELAYED, CANCELLED) - Start and end dates - Project timeline view - Grid view - Project details
Views: - Grid view - Timeline view - Project details dialog
Channel Management¶
Supported Channels: - WhatsApp Lite (AppGain) - WhatsApp Cloud (Meta) - Facebook Messenger - Instagram Direct Messages - Telegram - TikTok - Email - SMS - ShrinkIt Push Notifications
Features: - Channel account CRUD operations - Channel connection/disconnection - Channel status tracking - Channel-specific settings - Webhook configuration - OAuth integration (Facebook, Instagram)
Webhooks¶
Features: - Webhook configuration management - Event subscription - HMAC signature verification - Webhook delivery logging - Retry mechanism - Webhook testing
Available Events:
- Contact events: contact.created, contact.updated, contact.assigned
- Deal events: deal.created, deal.updated, deal.stage.changed, deal.assigned
- Conversation events: conversation.created, conversation.assigned, conversation.status.changed
- Message events: message.received, message.sent
Webhook Request Format:
{
"event": "contact.created",
"timestamp": "2025-01-15T10:30:00Z",
"data": {
"id": "contact-uuid",
"first_name": "John",
"last_name": "Doe"
}
}
Headers:
- X-Webhook-Event - Event type
- X-Webhook-Timestamp - ISO timestamp
- X-Webhook-Signature - HMAC-SHA256 signature (if secret configured)
Team & Organization Management¶
Features: - Organization CRUD operations - User management (profiles) - Role-based access control (OWNER, ADMIN, AGENT) - Team invitations - Permission management - Organization switching - User profile management
Permissions:
- can_access_crm - Access CRM features
- can_access_pm - Access project management
- can_manage_team - Manage team members
- can_manage_settings - Manage organization settings
- can_send_messages - Send messages
- can_read_messages - Read messages
API Key Management¶
Features: - API key generation - API key permissions - API key expiration - API key prefix identification - API key security (hashed storage)
Error Handling¶
Standard Error Response¶
All APIs return errors in a consistent format:
HTTP Status Codes¶
200 OK- Successful request201 Created- Resource created successfully400 Bad Request- Invalid request parameters401 Unauthorized- Authentication required or invalid403 Forbidden- Insufficient permissions404 Not Found- Resource not found409 Conflict- Resource conflict (e.g., duplicate)422 Unprocessable Entity- Validation error500 Internal Server Error- Server error503 Service Unavailable- Service temporarily unavailable
Common Error Codes¶
AUTHENTICATION_FAILED- Authentication failedINVALID_API_KEY- Invalid API keyINSUFFICIENT_PERMISSIONS- Insufficient permissionsRESOURCE_NOT_FOUND- Resource not foundVALIDATION_ERROR- Request validation failedRATE_LIMIT_EXCEEDED- Rate limit exceededSERVICE_UNAVAILABLE- Service unavailable
Error Examples¶
401 Unauthorized:
403 Forbidden:
404 Not Found:
422 Unprocessable Entity:
{
"error": "Validation error",
"details": {
"field": "email",
"message": "Invalid email format"
},
"code": "VALIDATION_ERROR"
}
Rate Limits & Best Practices¶
Rate Limits¶
- Edge Functions: 100 requests per minute per organization
- REST API: 1000 requests per minute per organization
- External APIs: 500 requests per minute per API key
Rate limit headers are included in responses:
- X-RateLimit-Limit - Request limit
- X-RateLimit-Remaining - Remaining requests
- X-RateLimit-Reset - Reset timestamp
Best Practices¶
- Authentication:
- Store API keys securely
- Use environment variables for keys
- Rotate API keys regularly
-
Use Bearer tokens for internal requests
-
Error Handling:
- Always check response status codes
- Handle rate limit errors gracefully
- Implement retry logic with exponential backoff
-
Log errors for debugging
-
Performance:
- Use pagination for large datasets
- Use
selectparameter to fetch only needed fields - Use filters to reduce data transfer
-
Cache frequently accessed data
-
Data Management:
- Use bulk operations when possible (import functions)
- Batch related operations
- Use transactions for multi-step operations
-
Validate data before sending
-
Webhooks:
- Verify HMAC signatures
- Handle webhook failures gracefully
- Implement idempotency for webhook handlers
-
Respond quickly (within 5 seconds)
-
Security:
- Never expose API keys in client-side code
- Use HTTPS for all requests
- Validate and sanitize all inputs
- Implement proper access controls
Postman Collection¶
A complete Postman collection is available at:
docs/api/ConnectGain_API.postman_collection.json
Setting Up Postman¶
- Import the collection into Postman
- Set collection variables:
url:https://txpaxbxhnvnhsjwwaeoy.supabase.coanon_key: Your Supabase anon keyapi_key: Your ConnectGain API key (for external APIs)organization_id: Your organization UUID-
Other resource IDs as needed
-
Start testing APIs!
Collection Structure¶
The collection is organized into folders: - Edge Functions - Message Sending - Edge Functions - Search & Import - Edge Functions - External APIs - Edge Functions - Organization & Auth - Edge Functions - Payment & Subscription - Edge Functions - Webhooks - REST API - Contacts - REST API - Companies - REST API - Deals - REST API - Pipelines - REST API - Conversations - REST API - Messages - REST API - Tasks - REST API - Templates - REST API - Bot Flows - REST API - Automation Rules - REST API - Campaigns - REST API - Notes - REST API - Channel Accounts - REST API - Projects - REST API - Organizations & Users
Support & Resources¶
- Documentation: This file and other docs in
/docs - Dashboard: https://supabase.com/dashboard
- API Base URL:
https://txpaxbxhnvnhsjwwaeoy.supabase.co - Postman Collection:
docs/api/ConnectGain_API.postman_collection.json
Documentation Version: 3.0.0 Last Updated: January 2025 Status: Production Ready