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.

Version 0.1.0 — September 2026MageTech AI Marketing OS is an enterprise-grade, AI-powered marketing operating system designed for businesses of all sizes — from individual sellers and freelancers to agencies and enterprises.

System Architecture

The platform follows a multi-layered microservices-inspired architecture within a Turborepo monorepo. Each layer is independently scalable.

Client Layer
Next.js 14 Web AppReact Native Expo MobileAPI Consumers / Webhooks
API Layer (Express.js - Port 3001)
Auth MiddlewareTenant MiddlewareRate Limiter28 Route Modules
Service Layer (27 Domain Modules)
Auth & UsersCRM & LeadsCampaignsAI OrchestratorEmail/WhatsApp/SMSSocial & AdsAutomationAnalytics
Background Workers (BullMQ + Redis)
Email QueueWhatsApp QueueSMS QueueAutomation QueueAI Queue
Data Layer
PostgreSQL 16 + pgvectorRedis 7 (Cache/Queue)AWS S3 (File Storage)

Technology Stack

LayerTechnologyVersionPurpose
MonorepoTurborepo + npm workspacesv2.1+Code organization, build caching
LanguageTypeScript5.5End-to-end type safety
FrontendNext.js (App Router)14SSR, routing, API routes
UI FrameworkReact + Tailwind CSS + Radix UI18 / 3Component library, styling
ChartsRecharts2.xAnalytics visualizations
Workflow BuilderReactFlow11Visual automation canvas
BackendExpress.js4.xREST API server
ORMPrisma5Database access, migrations
DatabasePostgreSQL + pgvector16Relational data + vector embeddings
Cache/QueueRedis + BullMQ7 / 5.xJob queues, caching, sessions
AIOpenAI SDK + Anthropic SDKLatestGPT-4o, Claude Sonnet 4
AuthJWT + bcrypt + speakeasyAccess/refresh tokens, MFA/TOTP
PaymentsStripeLatestSubscriptions, invoicing, webhooks
EmailSendGridv3 APITransactional & marketing email
SMSTwilioLatestSMS messaging
WhatsAppMeta Graph APIv18WhatsApp Business messaging
AdsMeta Ads API, Google Ads API, LinkedIn Marketing APIv18 / v16 / v2Paid advertising management
E-commerceShopify Admin API, WooCommerce REST API2024-01 / wc/v3Product & order sync
MobileReact Native + Expo0.86 / 57iOS/Android companion app
TestingJest + SupertestUnit & integration tests
CI/CDGitHub ActionsLint, test, build, deploy
ContainerizationDocker + Docker ComposeMulti-stageProduction deployment
Reverse ProxyNginxLatestSSL, 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

ModelPurpose
TenantRoot entity — plan type, Stripe billing, onboarding, settings JSON
UserUser accounts with MFA support, tied to tenant via tenantId
Role / UserRole / PermissionRBAC system with 11 roles and granular module-level permissions
InvitationTenant invitation system with expiring tokens
SessionJWT refresh token sessions
ApiKeyAPI key management with hash, prefix, expiry
AuditLogFull audit trail — action, entity, old/new data, IP, user agent

CRM & Lead Management

ModelPurpose
ContactFull contact records with lead score, tags, custom fields, owner
CompanyCompany records with industry, size, website
Deal / DealStageSales pipeline with value, currency, probability, stages
LeadFull lead lifecycle with AI scoring (cold/warm/hot/high_intent)
Activity / Task / NoteActivity logging, task management, pinnable notes
CustomField / TagDynamic custom fields and tagging system

Campaigns, Content & Channels

ModelPurpose
CampaignMulti-channel campaigns (10 types) with status lifecycle
EmailCampaign / EmailTemplateEmail campaigns with HTML, templates, open/click tracking
WhatsAppCampaign / WhatsAppTemplateWhatsApp campaigns with template support
SMSCampaign / SMSMessageSMS campaigns with Twilio tracking
AdCampaign / AdSet / AdMulti-platform ad campaigns (Meta/Google/LinkedIn)
SocialPost / SocialAccountSocial media posting and account management
ContentItem / ContentTemplateContent studio with 18 languages, 14 tones

AI & Automation

ModelPurpose
AIConversation / AIMessageAI chat conversations with tool calls/results
AIKnowledgeBase / AIDocumentChunkRAG knowledge base with document chunking and embeddings
Automation / AutomationNodeVisual automation workflows with trigger/action/condition nodes
Chatbot / ChatbotFlowChatbot builder with visual flow editor and knowledge base
AIUsageLogToken usage and cost tracking per model

Enterprise Features

ModelPurpose
Department / BranchOrganizational structure with multi-location support
Brand / BrandAssetMulti-brand management with guidelines and assets
ApprovalWorkflow / ApprovalRequestMulti-step approval processes with comments
SSOConfig / LDAPConfigEnterprise SSO (Google/Microsoft/Okta/Auth0/SAML) and LDAP
AgencyClientAsAgencyAgency-client relationship management
Segment / SegmentMemberDynamic 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

Environment Configuration

Copy .env.example to .env and configure the following:

Core Services

DATABASE_URL
PostgreSQL connection string
REDIS_URL
Redis connection string
JWT_SECRET
Access token signing key
JWT_REFRESH_SECRET
Refresh token signing key

AI Providers

OPENAI_API_KEY
Get from platform.openai.com
ANTHROPIC_API_KEY
Get from console.anthropic.com

Email (SendGrid)

SENDGRID_API_KEY
Get from app.sendgrid.com
SENDGRID_FROM_EMAIL
Verified sender email address

SMS (Twilio)

TWILIO_ACCOUNT_SID
Get from console.twilio.com
TWILIO_AUTH_TOKEN
Twilio auth token
TWILIO_PHONE_NUMBER
Twilio phone number (+1234567890)
 

WhatsApp (Meta)

WHATSAPP_ACCESS_TOKEN
Get from Meta for Developers
WHATSAPP_PHONE_NUMBER_ID
WhatsApp Business phone number ID

Payments (Stripe)

STRIPE_SECRET_KEY
Get from dashboard.stripe.com
STRIPE_WEBHOOK_SECRET
Webhook endpoint signing secret

Advertising

META_ACCESS_TOKEN
Meta Business Suite access token
GOOGLE_ADS_DEVELOPER_TOKEN
Google Ads API developer token
GOOGLE_ADS_CLIENT_ID
Google OAuth2 client ID
GOOGLE_ADS_CLIENT_SECRET
Google OAuth2 client secret

File Storage (AWS S3)

AWS_ACCESS_KEY_ID
IAM access key
AWS_SECRET_ACCESS_KEY
IAM secret key
AWS_REGION
S3 bucket region
S3_BUCKET_NAME
S3 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)

RoleKey Permissions
OwnerFull access (*). Manage billing, users, settings.
AdminManage users, campaigns, contacts, analytics, billing view.
ManagerCreate/send campaigns, manage contacts, view analytics.
Marketing ManagerCreate/send campaigns, manage content, view analytics.
Sales ManagerManage contacts, deals, leads, view sales analytics.
ViewerView-only access to all modules.

Adding Users

  1. Navigate to Settings > Team or Users & Roles
  2. Click "Invite User"
  3. Enter email, select role, assign branch (optional)
  4. User receives invitation email with expiring token
  5. 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

Email WhatsApp SMS Social Media Google Ads Meta Ads LinkedIn Ads Content Marketing Landing Page Mixed (Multi-channel)

Campaign Lifecycle

draft → scheduled → active → paused → completed
                         ↓
                    cancelled

5-Step Wizard

  1. Campaign Details — Name, type, description, budget
  2. Audience — Segment selection, contact filtering
  3. Content — Message creation, AI assistance, A/B testing
  4. Schedule — Send date/time, timezone, recurrence
  5. 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 TypeDescription
Social PostPlatform-optimized social media posts
Blog ArticleLong-form articles with SEO optimization
Email CampaignMarketing email copy with CTAs
Ad CopyPlatform-specific ad copywriting
Product DescriptionE-commerce product descriptions
Video ScriptYouTube/social video scripts
Landing PageHigh-converting landing page copy
NewsletterRegular 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)

New Lead Form Submission Tag Added Stage Changed Time-Based Webhook Email Opened Purchase Completed Cart Abandoned Schedule

Action Types (14)

Send Email Send WhatsApp Send SMS Create Task Update Lead Add/Remove Tag Assign User Call Webhook Notify User Update Deal Move Lead Stage

Condition Types

  • lead_score_above — Check lead score threshold
  • lead_source_is — Match lead source
  • has_tag — Check for specific tag
  • days_since_contacted — Time-based conditions
  • deal_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

  1. Overview — KPI cards, line/bar charts, trend indicators
  2. Leads — Funnel visualization, source breakdown, score distribution
  3. Campaigns — Performance by channel, A/B test results, ROI tracking
  4. Revenue — MRR, ARR, revenue by source, forecast
  5. Social — Engagement metrics, follower growth, best posts
  6. Email — Open rates, click rates, deliverability, list growth
  7. 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

PlatformAPIFeatures
FacebookGraph API v18.0Page posting, insights, engagement tracking
InstagramGraph API v18.0Media creation + publish, stories, insights
LinkedInMarketing API v2UGC posts, company page analytics
Twitter/XTwitter API v2Tweet creation, analytics
YouTubeData API v3Video 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

PlatformAPICampaign Types
Meta (Facebook/Instagram)Graph API v18.0Brand Awareness, Reach, Traffic, Conversions, Lead Gen
Google AdsGoogle Ads API v16Search, Display, Shopping, Performance Max, YouTube
LinkedInMarketing API v2Sponsored 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

CategoryNodes
MessageText, Image, Button, Quick Reply, Card
LogicCondition, Router
ActionsWebhook, Assign Agent, Add Tag, Send Email
AIGPT Response, Knowledge Base Search
TimingDelay (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

Hero Text Image Video Form FAQ Testimonials CTA Features

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

equals not_equals contains greater_than less_than in not_in before after

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

Campaign Content Budget General

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

Google Microsoft Okta Auth0 SAML 2.0 Custom OIDC

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

Row-Level Security (RLS) API Key Scoping JWT Tenant Claims Redis Key Prefixing

Plan-Based Limits

PlanPriceContactsEmails/moAI TokensUsers
Free$01001,00010K1
Starter$49/mo1,00010,000100K3
Growth$99/mo10,00050,000500K10
Professional$199/mo50,000200,0002M25
Enterprise$299/moUnlimitedUnlimitedUnlimitedUnlimited

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)

  1. Create account at sendgrid.com
  2. Go to Settings > API Keys > Create API Key
  3. Verify a single sender email or authenticate a domain
  4. Add to .env: SENDGRID_API_KEY and SENDGRID_FROM_EMAIL

2. WhatsApp Business

  1. Create app at developers.facebook.com
  2. Add WhatsApp product to your app
  3. Get temporary access token (or generate permanent token)
  4. Get Phone Number ID from WhatsApp > Getting Started
  5. Add to .env: WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID

3. SMS (Twilio)

  1. Create account at twilio.com
  2. Get Account SID and Auth Token from Console Dashboard
  3. Buy a phone number or use trial number
  4. Add to .env: TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER

4. Social Media

  1. Facebook/Instagram: Create Meta Business app, get Page Access Token
  2. LinkedIn: Create LinkedIn app, request Marketing API access
  3. Twitter/X: Create developer account, generate API keys
  4. Connect accounts via the Social Media module in the dashboard

5. Google Ads

  1. Apply for Google Ads API access at developers.google.com
  2. Get developer token, OAuth2 client ID and secret
  3. Generate refresh token via OAuth flow
  4. 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

  1. Create account at stripe.com
  2. Get API keys from Developers > API Keys
  3. Set up webhook endpoint: https://yourdomain.com/api/v1/billing/webhook
  4. Add to .env: STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY, STRIPE_WEBHOOK_SECRET

7. AI Providers

  1. OpenAI: Create account at platform.openai.com, generate API key
  2. Anthropic: Create account at console.anthropic.com, generate API key
  3. Add to .env: OPENAI_API_KEY and/or ANTHROPIC_API_KEY

8. E-commerce

  1. Shopify: Create custom app in Shopify Admin > Settings > Apps > Develop apps
  2. WooCommerce: Go to WooCommerce > Settings > Advanced > REST API > Add key
  3. Connect via the E-commerce module in the dashboard

User Management Guide

Adding Users

  1. Navigate to Settings > Team
  2. Click "Invite User"
  3. Enter email address and select a role
  4. Optional: Assign to a branch or department
  5. Click "Send Invitation"
  6. User receives email with invitation link (expires in 7 days)
  7. User clicks link, creates password, and sets up MFA (optional)

User Roles & Permissions

RoleCampaignsContactsAnalyticsSettingsBilling
OwnerFullFullFullFullFull
AdminFullFullFullFullView
ManagerCreate/SendFullViewLimited
MarketingCreate/SendViewView
SalesFullView
ViewerViewViewView

MFA Setup

  1. Go to Security settings
  2. Click "Enable MFA"
  3. Scan QR code with authenticator app (Google Authenticator, Authy, etc.)
  4. Enter verification code to confirm
  5. Save backup codes securely

Customer Benefits

For Small Businesses

For Agencies

For Enterprises

For E-commerce

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)

ModuleBase RouteDescription
Auth/api/v1/authLogin, register, MFA, password reset
Users/api/v1/usersUser CRUD, role management
Tenants/api/v1/tenantsTenant configuration, onboarding
CRM/api/v1/crmContacts, companies, deals, activities
Leads/api/v1/leadsLead capture, scoring, conversion
Campaigns/api/v1/campaignsMulti-channel campaign management
Content/api/v1/contentAI content generation, templates
AI/api/v1/aiAI chat, knowledge base, tools
Analytics/api/v1/analyticsDashboard, reports, insights
Email/api/v1/emailEmail campaigns, templates
WhatsApp/api/v1/whatsappWhatsApp campaigns, messaging
SMS/api/v1/smsSMS campaigns
Social/api/v1/socialSocial media posting, analytics
Ads/api/v1/adsMulti-platform ad management
Automation/api/v1/automationsVisual workflow builder
Chatbot/api/v1/chatbotChatbot builder, flows
Website/api/v1/websiteLanding pages, forms
E-commerce/api/v1/ecommerceProducts, cart, purchases
Segments/api/v1/segmentsAudience segmentation
Billing/api/v1/billingSubscriptions, invoices
Approvals/api/v1/approvalsApproval workflows
Audit/api/v1/auditAudit logs, compliance
SSO/api/v1/ssoSSO, LDAP, SCIM
Agency/api/v1/agencyMulti-client management
Settings/api/v1/settingsUser/tenant settings
Integrations/api/v1/integrationsThird-party connections
Branches/api/v1/branchesMulti-location management
Brands/api/v1/brandsBrand 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:

Webhook Events Handled


MageTech AI Marketing OS — Technical Documentation v0.1.0
Built with love by MageTech Solutions