MageTech AI Marketing OS
A full-featured, AI-powered multi-tenant SaaS marketing platform. From CRM and lead management to campaign orchestration, AI content generation, marketing automation, and analytics — all in one unified system.
System Architecture
The platform follows a multi-layered microservices-inspired architecture within a Turborepo monorepo. Each layer is independently scalable.
Technology Stack
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Monorepo | Turborepo + npm workspaces | v2.1+ | Code organization, build caching |
| Language | TypeScript | 5.5 | End-to-end type safety |
| Frontend | Next.js (App Router) | 14 | SSR, routing, API routes |
| UI Framework | React + Tailwind CSS + Radix UI | 18 / 3 | Component library, styling |
| Charts | Recharts | 2.x | Analytics visualizations |
| Workflow Builder | ReactFlow | 11 | Visual automation canvas |
| Backend | Express.js | 4.x | REST API server |
| ORM | Prisma | 5 | Database access, migrations |
| Database | PostgreSQL + pgvector | 16 | Relational data + vector embeddings |
| Cache/Queue | Redis + BullMQ | 7 / 5.x | Job queues, caching, sessions |
| AI | OpenAI SDK + Anthropic SDK | Latest | GPT-4o, Claude Sonnet 4 |
| Auth | JWT + bcrypt + speakeasy | — | Access/refresh tokens, MFA/TOTP |
| Payments | Stripe | Latest | Subscriptions, invoicing, webhooks |
| SendGrid | v3 API | Transactional & marketing email | |
| SMS | Twilio | Latest | SMS messaging |
| Meta Graph API | v18 | WhatsApp Business messaging | |
| Ads | Meta Ads API, Google Ads API, LinkedIn Marketing API | v18 / v16 / v2 | Paid advertising management |
| E-commerce | Shopify Admin API, WooCommerce REST API | 2024-01 / wc/v3 | Product & order sync |
| Mobile | React Native + Expo | 0.86 / 57 | iOS/Android companion app |
| Testing | Jest + Supertest | — | Unit & integration tests |
| CI/CD | GitHub Actions | — | Lint, test, build, deploy |
| Containerization | Docker + Docker Compose | Multi-stage | Production deployment |
| Reverse Proxy | Nginx | Latest | SSL, security headers, caching |
Monorepo Structure
magetech-ai-marketing-os/
├── apps/
│ ├── api/ # Express.js REST API (port 3001)
│ │ ├── prisma/ # Schema (113+ models), migrations, seed
│ │ └── src/
│ │ ├── ai/ # AI orchestrator, tools, RAG, safety
│ │ ├── automation/ # Actions, triggers, conditions
│ │ ├── config/ # Environment configuration
│ │ ├── controllers/ # Route handlers
│ │ ├── integrations/ # 9 platform integrations
│ │ ├── jobs/ # BullMQ job definitions
│ │ ├── middleware/ # Auth, tenant, rate limiting
│ │ ├── routes/ # 26 route modules
│ │ ├── services/ # 28 service modules
│ │ └── __tests__/ # Test files
│ ├── web/ # Next.js 14 Frontend (port 3000)
│ │ ├── app/ # App Router pages
│ │ │ ├── (auth)/ # Login, register, forgot-password
│ │ │ └── dashboard/ # 27 dashboard modules
│ │ ├── components/ # 11 component directories
│ │ ├── stores/ # Zustand state management
│ │ └── hooks/ # Custom React hooks
│ ├── mobile/ # React Native Expo App
│ └── worker/ # BullMQ Background Workers
├── packages/
│ ├── shared/ # Types, API client, validation, utils
│ ├── ui/ # Radix-based component library
│ ├── database/ # Prisma client
│ └── config/ # Shared ESLint, Tailwind, TypeScript
├── docker/ # Docker + Nginx configs
└── .github/workflows/ # CI/CD pipelines
Database Schema
The Prisma schema defines 113+ models across 20 functional domains using PostgreSQL with pgvector for AI vector embeddings.
Multi-Tenancy & Authentication
| Model | Purpose |
|---|---|
Tenant | Root entity — plan type, Stripe billing, onboarding, settings JSON |
User | User accounts with MFA support, tied to tenant via tenantId |
Role / UserRole / Permission | RBAC system with 11 roles and granular module-level permissions |
Invitation | Tenant invitation system with expiring tokens |
Session | JWT refresh token sessions |
ApiKey | API key management with hash, prefix, expiry |
AuditLog | Full audit trail — action, entity, old/new data, IP, user agent |
CRM & Lead Management
| Model | Purpose |
|---|---|
Contact | Full contact records with lead score, tags, custom fields, owner |
Company | Company records with industry, size, website |
Deal / DealStage | Sales pipeline with value, currency, probability, stages |
Lead | Full lead lifecycle with AI scoring (cold/warm/hot/high_intent) |
Activity / Task / Note | Activity logging, task management, pinnable notes |
CustomField / Tag | Dynamic custom fields and tagging system |
Campaigns, Content & Channels
| Model | Purpose |
|---|---|
Campaign | Multi-channel campaigns (10 types) with status lifecycle |
EmailCampaign / EmailTemplate | Email campaigns with HTML, templates, open/click tracking |
WhatsAppCampaign / WhatsAppTemplate | WhatsApp campaigns with template support |
SMSCampaign / SMSMessage | SMS campaigns with Twilio tracking |
AdCampaign / AdSet / Ad | Multi-platform ad campaigns (Meta/Google/LinkedIn) |
SocialPost / SocialAccount | Social media posting and account management |
ContentItem / ContentTemplate | Content studio with 18 languages, 14 tones |
AI & Automation
| Model | Purpose |
|---|---|
AIConversation / AIMessage | AI chat conversations with tool calls/results |
AIKnowledgeBase / AIDocumentChunk | RAG knowledge base with document chunking and embeddings |
Automation / AutomationNode | Visual automation workflows with trigger/action/condition nodes |
Chatbot / ChatbotFlow | Chatbot builder with visual flow editor and knowledge base |
AIUsageLog | Token usage and cost tracking per model |
Enterprise Features
| Model | Purpose |
|---|---|
Department / Branch | Organizational structure with multi-location support |
Brand / BrandAsset | Multi-brand management with guidelines and assets |
ApprovalWorkflow / ApprovalRequest | Multi-step approval processes with comments |
SSOConfig / LDAPConfig | Enterprise SSO (Google/Microsoft/Okta/Auth0/SAML) and LDAP |
AgencyClientAsAgency | Agency-client relationship management |
Segment / SegmentMember | Dynamic audience segmentation with rule engine |
Docker & Deployment
Development
# Start PostgreSQL + Redis
docker compose -f docker/docker-compose.yml up -d
# Services:
# PostgreSQL 16 (pgvector) - port 5432
# Redis 7 - port 6379
Production
# Full stack deployment
docker compose -f docker/docker-compose.prod.yml up -d
# Services:
# api - Express.js (port 3001)
# web - Next.js (port 3000)
# postgres - PostgreSQL 16 + pgvector
# redis - Redis 7 (AOF, 256MB limit)
# nginx - Reverse proxy (ports 80/443)
Nginx Configuration
- HTTP-to-HTTPS redirect with TLS 1.2/1.3
- Security headers: CSP, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy
- WebSocket upgrade support for real-time features
- Gzip compression for text/CSS/JS/JSON/SVG
- Immutable caching for
/_next/static/ - Proxy pass:
/api/to API,/to Web
Environment Configuration
Copy .env.example to .env and configure the following:
Core Services
DATABASE_URLPostgreSQL connection string
REDIS_URLRedis connection string
JWT_SECRETAccess token signing key
JWT_REFRESH_SECRETRefresh token signing key
AI Providers
Email (SendGrid)
SENDGRID_FROM_EMAILVerified sender email address
SMS (Twilio)
TWILIO_AUTH_TOKENTwilio auth token
TWILIO_PHONE_NUMBERTwilio phone number (+1234567890)
WhatsApp (Meta)
WHATSAPP_PHONE_NUMBER_IDWhatsApp Business phone number ID
Payments (Stripe)
STRIPE_WEBHOOK_SECRETWebhook endpoint signing secret
Advertising
META_ACCESS_TOKENMeta Business Suite access token
GOOGLE_ADS_DEVELOPER_TOKENGoogle Ads API developer token
GOOGLE_ADS_CLIENT_IDGoogle OAuth2 client ID
GOOGLE_ADS_CLIENT_SECRETGoogle OAuth2 client secret
File Storage (AWS S3)
AWS_ACCESS_KEY_IDIAM access key
AWS_SECRET_ACCESS_KEYIAM secret key
AWS_REGIONS3 bucket region
S3_BUCKET_NAMES3 bucket name
Authentication & Users
How It Works
JWT-based authentication with access tokens (15min) and refresh tokens (7 days). Supports MFA/TOTP via speakeasy, password reset flows, and API key management.
User Roles (11)
| Role | Key Permissions |
|---|---|
| Owner | Full access (*). Manage billing, users, settings. |
| Admin | Manage users, campaigns, contacts, analytics, billing view. |
| Manager | Create/send campaigns, manage contacts, view analytics. |
| Marketing Manager | Create/send campaigns, manage content, view analytics. |
| Sales Manager | Manage contacts, deals, leads, view sales analytics. |
| Viewer | View-only access to all modules. |
Adding Users
- Navigate to Settings > Team or Users & Roles
- Click "Invite User"
- Enter email, select role, assign branch (optional)
- User receives invitation email with expiring token
- User creates account and is added to the tenant
CRM & Leads
CRM Module
Full CRM with contacts, companies, deals, activities, tasks, and notes. Supports custom fields, tags, and lead source tracking.
Key Features
- Contact Management — CRUD with company association, tags, custom fields, lead score
- Deal Pipeline — Visual pipeline with stages: Prospecting → Qualification → Proposal → Negotiation → Closed Won/Lost
- Activity Logging — Track calls, emails, meetings, notes per contact/deal
- Task Management — Priority-based tasks (low/medium/high/urgent) with status tracking
- Import/Export — CSV import for contacts and leads
Leads Module
AI-powered lead management with scoring, pipeline stages, and conversion tracking.
- Lead Scoring — AI evaluates: Cold (<30), Warm (30-59), Hot (60-79), High Intent (80+)
- Pipeline View — Kanban board: New → Contacted → Qualified → Proposal → Negotiation → Won/Lost
- Conversion — Convert leads to CRM contacts/deals with one click
- Auto-Assignment — Round-robin or rule-based lead assignment
- Batch Scoring — Score multiple leads at once
Campaign Management
How It Works
Multi-channel campaign orchestration supporting 10 campaign types with a 5-step creation wizard.
Campaign Types
Campaign Lifecycle
draft → scheduled → active → paused → completed
↓
cancelled
5-Step Wizard
- Campaign Details — Name, type, description, budget
- Audience — Segment selection, contact filtering
- Content — Message creation, AI assistance, A/B testing
- Schedule — Send date/time, timezone, recurrence
- Review & Launch — Preview, confirm, launch
MageAI & Content Studio
AI Orchestrator
Multi-provider AI system with automatic fallback chain: GPT-4o → Claude Sonnet 4 → GPT-4o-mini. Supports tool calling, RAG augmentation, and safety guardrails.
Key Features
- Chat Interface — Multi-turn conversations with markdown rendering and tool call visualization
- 10 AI Tools — CRM queries, content generation, campaign creation, analytics queries
- RAG Pipeline — Document chunking, pgvector embeddings, semantic search
- Content Safety — Jailbreak detection, PII filtering, spam detection, prompt injection prevention
Content Studio
AI-powered content generation supporting 8 content types, 14 tones, and 18 languages.
| Content Type | Description |
|---|---|
| Social Post | Platform-optimized social media posts |
| Blog Article | Long-form articles with SEO optimization |
| Email Campaign | Marketing email copy with CTAs |
| Ad Copy | Platform-specific ad copywriting |
| Product Description | E-commerce product descriptions |
| Video Script | YouTube/social video scripts |
| Landing Page | High-converting landing page copy |
| Newsletter | Regular newsletter content |
Knowledge Base (RAG)
- Upload documents (PDF, DOCX, CSV, MD) or crawl websites
- Documents are chunked and embedded using pgvector
- Semantic search retrieves relevant context for AI responses
- Per-tenant knowledge base isolation
Marketing Automation
Visual Workflow Builder
Node-graph automation with triggers, actions, conditions, and delays. Build complex multi-step marketing workflows visually.
Trigger Types (12)
Action Types (14)
Condition Types
lead_score_above— Check lead score thresholdlead_source_is— Match lead sourcehas_tag— Check for specific tagdays_since_contacted— Time-based conditionsdeal_value_above— Deal value threshold
Analytics
How It Works
Real-time analytics engine with 7 dashboard tabs, AI-powered anomaly detection, and period-over-period comparisons.
Analytics Tabs
- Overview — KPI cards, line/bar charts, trend indicators
- Leads — Funnel visualization, source breakdown, score distribution
- Campaigns — Performance by channel, A/B test results, ROI tracking
- Revenue — MRR, ARR, revenue by source, forecast
- Social — Engagement metrics, follower growth, best posts
- Email — Open rates, click rates, deliverability, list growth
- AI Insights — Automated trend detection, optimization suggestions
AI-Powered Features
- Anomaly Detection — Automatically flags unusual metric changes with severity levels
- Period Comparison — Compare any two time periods side-by-side
- Predictive Analytics — Revenue forecasting and trend projection
- Smart Recommendations — AI suggests optimization actions based on data patterns
Email Marketing
Integration: SendGrid API v3
- Email campaign creation with HTML/text content
- Template management with variable interpolation
- Open/click/bounce/unsubscribe tracking
- Segment-based recipient targeting (8 preset segments)
- A/B testing support
- Scheduled sending with timezone support
Configuration
Set SENDGRID_API_KEY and SENDGRID_FROM_EMAIL in .env. Get API key from SendGrid Dashboard.
WhatsApp Business
Integration: Meta Graph API v18
- Text, template, image, document, and interactive messages
- Template management and registration
- Read receipts and delivery tracking
- Real-time chat inbox with conversation threads
- Bulk messaging support
Configuration
Set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID. Get credentials from Meta for Developers > WhatsApp > Getting Started.
SMS Marketing
Integration: Twilio REST API
- Single and batch SMS sending
- Message status tracking (sent/delivered/failed)
- SMS template management
- Available phone number lookup
Configuration
Set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_PHONE_NUMBER. Get credentials from Twilio Console.
Social Media
Supported Platforms
| Platform | API | Features |
|---|---|---|
| Graph API v18.0 | Page posting, insights, engagement tracking | |
| Graph API v18.0 | Media creation + publish, stories, insights | |
| Marketing API v2 | UGC posts, company page analytics | |
| Twitter/X | Twitter API v2 | Tweet creation, analytics |
| YouTube | Data API v3 | Video upload, channel analytics |
Features
- Visual content calendar with post scheduling
- Multi-platform post creation and publishing
- Engagement metrics (likes, comments, shares, reach)
- Recommended posting times per platform
- Draft management and post queue
Ad Manager
Supported Platforms
| Platform | API | Campaign Types |
|---|---|---|
| Meta (Facebook/Instagram) | Graph API v18.0 | Brand Awareness, Reach, Traffic, Conversions, Lead Gen |
| Google Ads | Google Ads API v16 | Search, Display, Shopping, Performance Max, YouTube |
| Marketing API v2 | Sponsored Content, Message Ads, Text Ads |
Features
- 5-step ad creation wizard (Platform → Details → Audience → Creative → Review)
- Audience targeting (age, interests, location, custom audiences)
- Performance metrics: impressions, clicks, CTR, CPC, conversions, ROAS
- Budget management with daily/lifetime budgets
- Campaign lifecycle: pause, resume, complete
Chatbot Builder
Visual Flow Builder
Drag-and-drop chatbot builder with multi-step conversational flows and live chat testing.
Node Types
| Category | Nodes |
|---|---|
| Message | Text, Image, Button, Quick Reply, Card |
| Logic | Condition, Router |
| Actions | Webhook, Assign Agent, Add Tag, Send Email |
| AI | GPT Response, Knowledge Base Search |
| Timing | Delay (minutes/hours/days) |
Features
- Knowledge base linking for AI-powered responses
- Agent handoff for human support
- Live chat inbox with conversation history
- Chatbot statistics and performance tracking
Website Builder
Block-Based Landing Page Builder
Create landing pages with draggable content blocks and AI-powered generation.
Block Types
Form Builder
Custom forms with field types: text, email, phone, textarea, select, checkbox. Submission tracking and export.
E-commerce
Integrations: Shopify & WooCommerce
- Shopify — Admin API 2024-01: Products, orders, customers, abandoned cart recovery
- WooCommerce — REST API wc/v3: Products, orders, customers, coupons, sales reports
Features
- Product catalog management with categories and tags
- AI-powered product recommendations (frequently bought, upsell, cross-sell)
- Cart abandonment tracking and recovery
- Purchase history and top customer analytics
Audience Segments
Rule-Based Segmentation
Create dynamic or static audience segments using field-level rules with AND/OR logic.
Rule Operators
Preset Segments
- New Leads (last 7 days)
- Hot Leads (score ≥ 60)
- Inactive Customers (no activity 30+ days)
- High-Value Deals (value ≥ $10,000)
Approval Workflows
Multi-Step Approval System
Configurable approval workflows for campaigns, content, and budget changes.
Approval Types
Workflow Features
- Drag-and-drop workflow builder with ordered steps
- Request lifecycle: Submit → Review → Approve/Reject/Revision
- Comment system for feedback and discussion
- Email notifications for pending approvals
- Timeout and auto-approve threshold settings
SSO & Enterprise Security
Supported SSO Providers
LDAP Integration
- Custom LDAP v3 client (no external dependency)
- LDAP over TLS (ldaps://) support
- User sync from LDAP directory
- Connection testing with latency measurement
SCIM Provisioning
Automated user provisioning and deprovisioning via SCIM 2.0 protocol.
Security Policies
- MFA enforcement (TOTP, SMS backup)
- Password complexity requirements
- Session timeout configuration
- Account lockout after failed attempts
- IP whitelist/blacklist
Agency / Multi-Client
How It Works
Manage multiple client accounts from a single agency dashboard. Each client has isolated data, configurable permissions, and white-label options.
Client Permissions
- Campaign editing
- Contact management
- Analytics access
- Billing visibility
- AI feature access
White-Label Settings
- Custom domain per client
- Custom branding (logo, colors)
- Custom email templates
- Client-facing dashboard
Multi-Tenant Architecture
Data Isolation
Every database model includes a tenantId with cascade delete. Data isolation is enforced at the service layer.
Isolation Methods
Plan-Based Limits
| Plan | Price | Contacts | Emails/mo | AI Tokens | Users |
|---|---|---|---|---|---|
| Free | $0 | 100 | 1,000 | 10K | 1 |
| Starter | $49/mo | 1,000 | 10,000 | 100K | 3 |
| Growth | $99/mo | 10,000 | 50,000 | 500K | 10 |
| Professional | $199/mo | 50,000 | 200,000 | 2M | 25 |
| Enterprise | $299/mo | Unlimited | Unlimited | Unlimited | Unlimited |
Corporate / Enterprise Structure
Organization Features
- Departments — Organize users into departments (Marketing, Sales, Support, etc.)
- Branches — Multi-location management with timezone, currency, locale, working hours
- Brands — Multi-brand management with guidelines, assets, and performance tracking
- Hierarchy — Visual org chart with parent-child relationships
Branch Configuration
- Address, timezone, currency, locale
- Working hours per day
- Holiday management
- User-to-branch assignment
- Performance tracking per branch
Audit Logs
Comprehensive Audit Trail
Every action in the system is logged with full context for compliance and security.
Logged Data
- Timestamp, user, action type (CREATE/UPDATE/DELETE/LOGIN/SEND/AI_GEN)
- Entity type and ID
- Old and new data (for updates)
- IP address and user agent
- Branch and brand context
Features
- Date range filtering and search
- Export to CSV
- Entity history tracking (see all changes to a specific contact/deal)
- User activity tracking
- Action breakdown analytics
- Data retention management
Integration Setup Guide
Step-by-Step Configuration
1. Email (SendGrid)
- Create account at sendgrid.com
- Go to Settings > API Keys > Create API Key
- Verify a single sender email or authenticate a domain
- Add to
.env:SENDGRID_API_KEYandSENDGRID_FROM_EMAIL
2. WhatsApp Business
- Create app at developers.facebook.com
- Add WhatsApp product to your app
- Get temporary access token (or generate permanent token)
- Get Phone Number ID from WhatsApp > Getting Started
- Add to
.env:WHATSAPP_ACCESS_TOKENandWHATSAPP_PHONE_NUMBER_ID
3. SMS (Twilio)
- Create account at twilio.com
- Get Account SID and Auth Token from Console Dashboard
- Buy a phone number or use trial number
- Add to
.env:TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN,TWILIO_PHONE_NUMBER
4. Social Media
- Facebook/Instagram: Create Meta Business app, get Page Access Token
- LinkedIn: Create LinkedIn app, request Marketing API access
- Twitter/X: Create developer account, generate API keys
- Connect accounts via the Social Media module in the dashboard
5. Google Ads
- Apply for Google Ads API access at developers.google.com
- Get developer token, OAuth2 client ID and secret
- Generate refresh token via OAuth flow
- Add to
.env:GOOGLE_ADS_DEVELOPER_TOKEN,GOOGLE_ADS_CLIENT_ID,GOOGLE_ADS_CLIENT_SECRET,GOOGLE_ADS_REFRESH_TOKEN,GOOGLE_ADS_CUSTOMER_ID
6. Stripe Billing
- Create account at stripe.com
- Get API keys from Developers > API Keys
- Set up webhook endpoint:
https://yourdomain.com/api/v1/billing/webhook - Add to
.env:STRIPE_SECRET_KEY,STRIPE_PUBLISHABLE_KEY,STRIPE_WEBHOOK_SECRET
7. AI Providers
- OpenAI: Create account at platform.openai.com, generate API key
- Anthropic: Create account at console.anthropic.com, generate API key
- Add to
.env:OPENAI_API_KEYand/orANTHROPIC_API_KEY
8. E-commerce
- Shopify: Create custom app in Shopify Admin > Settings > Apps > Develop apps
- WooCommerce: Go to WooCommerce > Settings > Advanced > REST API > Add key
- Connect via the E-commerce module in the dashboard
User Management Guide
Adding Users
- Navigate to Settings > Team
- Click "Invite User"
- Enter email address and select a role
- Optional: Assign to a branch or department
- Click "Send Invitation"
- User receives email with invitation link (expires in 7 days)
- User clicks link, creates password, and sets up MFA (optional)
User Roles & Permissions
| Role | Campaigns | Contacts | Analytics | Settings | Billing |
|---|---|---|---|---|---|
| Owner | Full | Full | Full | Full | Full |
| Admin | Full | Full | Full | Full | View |
| Manager | Create/Send | Full | View | Limited | — |
| Marketing | Create/Send | View | View | — | — |
| Sales | — | Full | View | — | — |
| Viewer | View | View | View | — | — |
MFA Setup
- Go to Security settings
- Click "Enable MFA"
- Scan QR code with authenticator app (Google Authenticator, Authy, etc.)
- Enter verification code to confirm
- Save backup codes securely
Customer Benefits
For Small Businesses
- All-in-One Platform — No need for 5+ separate tools (email, CRM, social, analytics, ads)
- AI-Powered Content — Generate professional marketing content in seconds
- Automated Workflows — Set up once, run forever — welcome emails, lead nurturing, cart recovery
- Multi-Channel Reach — Email, WhatsApp, SMS, Social, Ads from one dashboard
- Free Tier — Start free, upgrade as you grow
For Agencies
- Multi-Client Management — Manage 10-100+ clients from one dashboard
- White-Label Options — Custom domains, branding per client
- Client Health Scoring — Proactively identify at-risk accounts
- Permission Controls — Granular access per client
- Revenue Tracking — Track client revenue and ROI
For Enterprises
- Multi-Tenant Isolation — Complete data isolation with row-level security
- SSO/LDAP — Enterprise single sign-on and directory integration
- Approval Workflows — Multi-step approval for campaigns and content
- Audit Logging — Full compliance trail for every action
- Unlimited Scale — Enterprise plan with no limits
For E-commerce
- Shopify/WooCommerce Integration — Sync products, orders, customers
- Cart Abandonment Recovery — Automated WhatsApp/email recovery sequences
- AI Recommendations — Product recommendations for cross-sell/upsell
- Purchase Tracking — Revenue attribution per campaign/channel
API Reference
Base URL
http://localhost:3001/api/v1
Authentication
Authorization: Bearer <your-jwt-token>
Request Format
POST /api/v1/contacts
Content-Type: application/json
Authorization: Bearer <token>
{
"firstName": "John",
"lastName": "Doe",
"email": "john@example.com"
}
Response Format
{
"success": true,
"data": { ... },
"message": "Optional message",
"pagination": {
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5
}
}
API Modules (28)
| Module | Base Route | Description |
|---|---|---|
| Auth | /api/v1/auth | Login, register, MFA, password reset |
| Users | /api/v1/users | User CRUD, role management |
| Tenants | /api/v1/tenants | Tenant configuration, onboarding |
| CRM | /api/v1/crm | Contacts, companies, deals, activities |
| Leads | /api/v1/leads | Lead capture, scoring, conversion |
| Campaigns | /api/v1/campaigns | Multi-channel campaign management |
| Content | /api/v1/content | AI content generation, templates |
| AI | /api/v1/ai | AI chat, knowledge base, tools |
| Analytics | /api/v1/analytics | Dashboard, reports, insights |
/api/v1/email | Email campaigns, templates | |
/api/v1/whatsapp | WhatsApp campaigns, messaging | |
| SMS | /api/v1/sms | SMS campaigns |
| Social | /api/v1/social | Social media posting, analytics |
| Ads | /api/v1/ads | Multi-platform ad management |
| Automation | /api/v1/automations | Visual workflow builder |
| Chatbot | /api/v1/chatbot | Chatbot builder, flows |
| Website | /api/v1/website | Landing pages, forms |
| E-commerce | /api/v1/ecommerce | Products, cart, purchases |
| Segments | /api/v1/segments | Audience segmentation |
| Billing | /api/v1/billing | Subscriptions, invoices |
| Approvals | /api/v1/approvals | Approval workflows |
| Audit | /api/v1/audit | Audit logs, compliance |
| SSO | /api/v1/sso | SSO, LDAP, SCIM |
| Agency | /api/v1/agency | Multi-client management |
| Settings | /api/v1/settings | User/tenant settings |
| Integrations | /api/v1/integrations | Third-party connections |
| Branches | /api/v1/branches | Multi-location management |
| Brands | /api/v1/brands | Brand management |
Billing & Plans
Stripe Integration
Billing is powered by Stripe with webhook-driven subscription management.
Subscription Lifecycle
Create Subscription → Active → Past Due → Canceled
↓
Trial Period
Usage Tracking
Each plan has configurable limits. Usage is tracked in real-time:
- Contacts, leads, campaigns, automations
- Email sends, SMS sends, WhatsApp messages
- AI token usage, storage, API calls
- Team members, social accounts
Webhook Events Handled
checkout.session.completed— New subscriptioninvoice.paid— Payment successfulinvoice.payment_failed— Payment failedcustomer.subscription.updated— Plan changecustomer.subscription.deleted— Cancellation
MageTech AI Marketing OS — Technical Documentation v0.1.0
Built with love by MageTech Solutions