Technical Documentation v1.0.0 WHMCS 9.1.x · PHP 8.2–8.4

Haikhavan Cloudflare Connect & Analytics

Complete architecture reference, installation guide, database schema, hooks, and troubleshooting.

Quick Installation

  1. Purchase the module and download haikhavan_cloudflare_connect-ioncube-8.2-1.0.0-install.zip from your VPSrv Client Area Downloads.
  2. Upload and extract the ZIP into your WHMCS root directory so files land in modules/addons/haikhavan_cloudflare_connect/.
  3. Verify PHP 8.2–8.4 with ionCube PHP Loader 14+ / 15.5+ is enabled on your server.
  4. Go to System Settings → Addon Modules in WHMCS Admin, click Activate next to Haikhavan Cloudflare Connect & Analytics, and assign administrator role access.

One-click Cloudflare onboarding, automated WHMCS registrar nameserver synchronization, live activation verification, full plan-aware Cloudflare API management (Free / Pro / Business / Enterprise), and deep Admin traffic, threat, DNS & WAF event forensics.


Haikhavan Cloudflare Connect & Analytics — Technical Documentation (v1.0.0)

This specification documents the complete architecture, database schema, cryptographic design, Cloudflare REST v4 & GraphQL integrations, WHMCS hook contracts, plan-tier gating matrix, AJAX API endpoints, and operational troubleshooting for haikhavan_cloudflare_connect.


1. Architecture & File Inventory

The addon follows a clean PSR-4-style CloudflareConnect\ namespace autoloaded in both haikhavan_cloudflare_connect.php and hooks.php without external Composer dependencies.

modules/addons/haikhavan_cloudflare_connect/
├── haikhavan_cloudflare_connect.php         # WHMCS addon lifecycle hooks (_config, _activate, _deactivate, _upgrade, _output, _clientarea)
├── hooks.php                      # 6 WHMCS hooks (Navbar, Sidebar, Footer CTA, Admin Domain Tab, Admin Home Widget, Daily Cron)
├── whmcs.json                     # WHMCS Marketplace manifest (schema 1.0)
├── lib/
│   ├── Database.php               # Capsule schema DDL, settings loader, AES-256-CBC+HMAC crypto, account/zone/audit CRUD
│   ├── CloudflareClient.php       # Native cURL REST v4 + GraphQL API client & pre-filled Create API Token deep-link builder
│   ├── DomainConnector.php        # Client/zone credential resolver, 6-step onboarding orchestrator, localAPI NS sync, activation verification
│   ├── FeatureCatalog.php         # Authoritative 4-tier (Free/Pro/Business/Enterprise) feature catalog, quotas, UI evaluator, mutation validator
│   ├── AnalyticsService.php       # GraphQL HTTP/WAF/DNS analytics engine, snapshot caching, Admin Fleet aggregator, formatters
│   ├── ClientController.php       # Client Area Smarty page renderer + 28-operation CSRF-protected JSON AJAX router
│   ├── AdminController.php        # Admin PHP view renderer (Fleet Dashboard, Deep Domain Stats) + 8-operation Admin AJAX router
│   └── SandboxSimulator.php       # Deterministic offline Cloudflare API + GraphQL simulator for local testing & demos
├── templates/
│   ├── client/
│   │   ├── overview.tpl           # Client account connection & purchased domain list
│   │   └── manage.tpl             # 10-tab per-domain Cloudflare control panel
│   └── admin/
│       ├── dashboard.php          # Fleet KPIs, Connected Domains table, Provider Account setup, Audit Log
│       └── domain_stats.php       # Deep per-domain Canvas charts, WAF breakdowns, Top IPs/Countries, live WAF stream, DNS stats
└── assets/
    ├── css/haikhavan_cloudflare_connect.css # Scoped .hk-cf-* stylesheet, plan tier badges, responsive tables & cards
    └── js/haikhavan_cloudflare_connect.js   # Vanilla JS AJAX engine, inline Canvas chart renderer, WAF stream live search/filter

2. Database Schema (4 Custom Tables)

Created idempotently via WHMCS\Database\Capsule::schema() in Database::install(). All tables are preserved on module deactivation.

2.1 mod_hk_cf_accounts

Stores encrypted Cloudflare API credentials for WHMCS clients (userid > 0) and the optional Admin Provider account (userid = 0).

Column Type Attributes Description
id INT UNSIGNED PK, AUTO_INCREMENT Primary key
userid INT UNSIGNED DEFAULT 0, UNIQUE, INDEX WHMCS client ID (0 = Admin Provider account)
auth_type VARCHAR(20) DEFAULT 'token' token (Scoped API Token) or global_key (Global API Key)
email VARCHAR(191) NULL Cloudflare email (required for global_key, optional for token)
credential_encrypted TEXT NOT NULL v1: AES-256-CBC + HMAC-SHA256 encrypted token/key
cf_account_id VARCHAR(64) NULL Active Cloudflare Account ID
cf_account_name VARCHAR(191) NULL Active Cloudflare Account Display Name
available_accounts_json TEXT NULL JSON array of all Cloudflare accounts accessible to the credential
token_status VARCHAR(32) DEFAULT 'active' Verification status returned by Cloudflare
verified_at TIMESTAMP NULL Last successful credential verification timestamp
created_at / updated_at TIMESTAMP NULL Standard Eloquent timestamps

2.2 mod_hk_cf_zones

Maps each connected WHMCS domain (tbldomains.id) to its Cloudflare Zone ID, plan tier, nameservers, and sync state.

Column Type Attributes Description
id INT UNSIGNED PK, AUTO_INCREMENT Primary key
userid INT UNSIGNED INDEX Owning WHMCS client ID
domainid INT UNSIGNED UNIQUE Foreign reference to tbldomains.id
domain VARCHAR(255) INDEX Lowercase domain name
cf_account_record_id INT UNSIGNED NULL Foreign reference to mod_hk_cf_accounts.id
use_provider_account TINYINT DEFAULT 0 1 if onboarded under Admin Provider account (userid=0)
cf_account_id VARCHAR(64) NULL Cloudflare Account ID hosting the zone
zone_id VARCHAR(64) INDEX Cloudflare Zone Tag / ID
zone_status VARCHAR(32) DEFAULT 'pending' pending, active, moved, deactivated, initializing
plan_id VARCHAR(64) DEFAULT 'free' Normalized tier: free, pro, business, enterprise
plan_name VARCHAR(128) DEFAULT 'Free Website' Raw Cloudflare plan label
plan_raw_json TEXT NULL Raw Cloudflare zone.plan object JSON
assigned_nameservers_json TEXT NULL JSON array of Cloudflare assigned NS hostnames
original_nameservers_json TEXT NULL JSON array of pre-Cloudflare NS hostnames
ns_sync_status VARCHAR(32) DEFAULT 'pending' pending, synced, manual_required, failed
ns_sync_message TEXT NULL Human-readable result of last registrar NS push
paused TINYINT DEFAULT 0 1 when Cloudflare proxy is paused (DNS-only mode)
development_mode TINYINT DEFAULT 0 1 when 3-hour Development Mode bypass is active
last_activation_check_at TIMESTAMP NULL Timestamp of last PUT /activation_check
last_synced_at TIMESTAMP NULL Timestamp of last metadata sync
created_at / updated_at TIMESTAMP NULL Standard Eloquent timestamps

2.3 mod_hk_cf_stats_cache

Caches aggregated and detailed GraphQL telemetry per connected zone and timeframe (6h, 24h, 7d, 30d).

Column Type Attributes Description
id INT UNSIGNED PK, AUTO_INCREMENT Primary key
zone_record_id INT UNSIGNED INDEX Foreign reference to mod_hk_cf_zones.id
zone_id VARCHAR(64) INDEX Cloudflare Zone ID
timeframe VARCHAR(16) DEFAULT '24h' 6h, 24h, 7d, or 30d
requests_total BIGINT UNSIGNED DEFAULT 0 Total HTTP edge requests
requests_cached BIGINT UNSIGNED DEFAULT 0 Cached HTTP edge requests
bytes_total BIGINT UNSIGNED DEFAULT 0 Total bandwidth transferred (bytes)
bytes_cached BIGINT UNSIGNED DEFAULT 0 Bandwidth served from edge cache (bytes)
threats_total BIGINT UNSIGNED DEFAULT 0 Total threats mitigated
waf_events_total BIGINT UNSIGNED DEFAULT 0 Total WAF / firewall events
uniques_total BIGINT UNSIGNED DEFAULT 0 Unique visitors
dns_queries_total BIGINT UNSIGNED DEFAULT 0 Authoritative DNS query count
payload_json LONGTEXT NULL Complete normalized analytics JSON (timeseries, status codes, countries, TLS, content types, WAF breakdown, recent events, DNS)
fetched_at TIMESTAMP NULL Cache freshness timestamp (checked against stats_cache_minutes)
created_at / updated_at TIMESTAMP NULL Standard timestamps
(Composite Unique) UNIQUE (zone_record_id, timeframe) One cached snapshot per zone per timeframe

2.4 mod_hk_cf_activity_log

Immutable audit trail of all onboarding, DNS, WAF, cache purge, feature toggle, and admin provider operations.

Column Type Attributes Description
id INT UNSIGNED PK, AUTO_INCREMENT Primary key
userid INT UNSIGNED DEFAULT 0, INDEX Acting or affected WHMCS client ID
adminid INT UNSIGNED DEFAULT 0, INDEX Acting WHMCS admin ID (populated from $_SESSION['adminid'])
domainid INT UNSIGNED DEFAULT 0, INDEX Affected WHMCS domain ID
domain VARCHAR(255) NULL Domain name snapshot
action VARCHAR(64) INDEX Action identifier (e.g., connect_domain, sync_nameservers, update_feature, dns_create, waf_rule_create, purge_cache)
status VARCHAR(20) DEFAULT 'success' success, warning, or error
summary TEXT NULL Human-readable event description
details_json TEXT NULL Structured metadata JSON
ip_address VARCHAR(64) NULL Requestor IP ($_SERVER['REMOTE_ADDR'])
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP Event timestamp

3. Security & Cryptographic Specification

3.1 Credential Encryption at Rest (AES-256-CBC + HMAC-SHA256)

Implemented in Database::encryptSecret() and Database::decryptSecret():

  1. Master Key Resolution (getEncryptionKeyMaterial()): Reads WHMCS $cc_encryption_hash in order from $GLOBALS['cc_encryption_hash'], \WHMCS\Config\Application::getInstance()['cc_encryption_hash'], or parses ROOTDIR/configuration.php.
  2. Domain-Separated Subkeys: Derives two independent 256-bit binary keys via HMAC-SHA256:
    • Encryption key: $encKey = hash_hmac('sha256', 'cf_connect_enc_v1', $keyMaterial, true)
    • Authentication key: $macKey = hash_hmac('sha256', 'cf_connect_mac_v1', $keyMaterial, true)
  3. Authenticated Encryption (Encrypt-then-MAC):
    • Generates a fresh CSPRNG 16-byte IV (random_bytes(16)).
    • Encrypts plaintext using openssl_encrypt($plaintext, 'AES-256-CBC', $encKey, OPENSSL_RAW_DATA, $iv).
    • Computes MAC over IV + ciphertext: $mac = hash_hmac('sha256', $iv . $ciphertext, $macKey, true) (32 bytes).
    • Stores versioned envelope: 'v1:' . base64_encode($iv . $mac . $ciphertext).
  4. Constant-Time Verification on Decrypt: Decodes binary payload (minimum 49 bytes), recomputes $calcMac, verifies with hash_equals($mac, $calcMac) before decrypting to prevent padding-oracle or tampering attacks.

3.2 Authorization, CSRF & Input Safety

  • CSRF Protection: Separate 48-hex-char session tokens ($_SESSION['hk_cf_csrf'] for clients; $_SESSION['hk_cf_admin_csrf'] for admins), validated via hash_equals() on all write AJAX operations (POST body csrf_token or X-CF-CSRF header).
  • Strict Tenant Isolation: ClientController::requireOwnedZone() verifies both domainid AND userid = $_SESSION['uid'] against mod_hk_cf_zones before any read/write operation.
  • Output Escaping: All admin PHP templates escape via htmlspecialchars(..., ENT_QUOTES, 'UTF-8'); all Smarty .tpl templates use |escape; JSON embedded in hooks uses JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT.

4. Cloudflare REST API v4 & GraphQL Analytics Endpoints

CloudflareClient::getCreateTokenUrl() generates a Cloudflare Dashboard URL (https://dash.cloudflare.com/profile/api-tokens) pre-populating 12 scoped permission groups (accountId=*, zoneId=all):

Permission Group Key Access Purpose
account_settings read Enumerate accessible Cloudflare accounts
account_analytics read Account-level telemetry read access
zone edit Create, read, pause, delete zones & trigger activation checks
dns edit Full DNS CRUD, DNS auto-scan, BIND import/export, DNSSEC
zone_settings edit SSL/TLS, Speed, Caching, Network, Scrape Shield zone settings
ssl edit Read edge certificate packs & SSL configuration
zone_waf edit Manage Custom WAF rulesets (http_request_firewall_custom)
firewall_services edit Manage IP Access Rules & Firewall services
cache_purge edit Purge everything, purge by URL, Enterprise purge by tag/host/prefix
page_rules edit Create, list, and delete Page Rules
zone_analytics read Execute GraphQL HTTP, WAF/Firewall, and DNS analytics queries
bot_management edit Toggle Bot Fight Mode / Super Bot Fight Mode

4.2 REST API v4 Routes (https://api.cloudflare.com/client/v4)

Domain Method & Endpoint Method in CloudflareClient
Auth GET /user/tokens/verify, GET /user, GET /accounts verifyCredentials(), listAccounts()
Zones GET /zones, GET /zones/{id}, POST /zones, PATCH /zones/{id}, DELETE /zones/{id}, PUT /zones/{id}/activation_check findZoneByName(), getZone(), createZone(), setZonePaused(), deleteZone(), activationCheck()
DNS & DNSSEC GET/POST /zones/{id}/dns_records, PATCH/DELETE /zones/{id}/dns_records/{rec}, POST /dns_records/scan, GET /dns_records/export, POST /dns_records/import, GET/PATCH /zones/{id}/dnssec listDnsRecords(), createDnsRecord(), updateDnsRecord(), deleteDnsRecord(), scanDnsRecords(), exportDnsRecords(), importDnsRecords(), getDnssec(), updateDnssec()
Settings GET /zones/{id}/settings, PATCH /zones/{id}/settings/{setting_id} getZoneSettings(), updateZoneSetting()
SSL & Edge Add-ons GET /zones/{id}/ssl/certificate_packs, GET/PATCH /argo/smart_routing, GET/PATCH /argo/tiered_caching, GET/PUT /bot_management, GET/PUT /page_shield, GET/POST /leaked-credential-checks, GET /custom_pages, GET /logpush/jobs listCertificatePacks(), get/updateArgoSmartRouting(), get/updateTieredCache(), get/updateBotManagement(), get/updatePageShield(), get/updateLeakedCredentials(), listCustomPages(), listLogpushJobs()
Cache Purge POST /zones/{id}/purge_cache (purge_everything, files, or tags/hosts/prefixes) purgeEverything(), purgeFiles(), purgeAdvanced()
WAF & Rules GET/PUT /zones/{id}/rulesets/phases/{phase}/entrypoint, GET/POST/DELETE /firewall/access_rules/rules, GET/POST/DELETE /pagerules getEntrypointRuleset(), putEntrypointRuleset(), list/create/deleteIpAccessRules(), list/create/deletePageRules()

4.3 GraphQL Analytics API (POST https://api.cloudflare.com/client/v4/graphql)

AnalyticsService executes 3 structured GraphQL queries per zone refresh:

  1. HTTP Traffic, Cache & Threats (queryHttpAnalytics):
    • 6h / 24h timeframes: httpRequests1hGroups (hourly buckets, up to 48 groups).
    • 7d / 30d timeframes: httpRequests1dGroups (daily buckets, up to 60 groups).
    • Extracted metrics: requests, cachedRequests, bytes, cachedBytes, threats, pageViews, uniq.uniques, responseStatusMap, countryMap, sslMap, and contentTypeMap.
  2. WAF & Firewall Forensics (queryWafAnalytics):
    • Aggregates via firewallEventsAdaptiveGroups: counts grouped by action, source, and top 10 attacking (clientIP, clientCountryName, clientAsn).
    • Raw recent event stream via firewallEventsAdaptive (limit 60, capped to 24h raw lookback for Free/Pro compatibility): datetime, action, source, ruleId, clientIP, clientCountryName, clientAsn, clientRequestHTTPMethodName, clientRequestHTTPHost, clientRequestPath, clientRequestQuery, userAgent, rayName.
  3. Authoritative DNS Telemetry (queryDnsAnalytics):
    • Queries dnsAnalyticsAdaptiveGroups grouped by queryType, responseCode, and top 10 queryName hostnames.

5. WHMCS Hooks (All 6 Registered Hooks)

All hooks are defined in modules/addons/haikhavan_cloudflare_connect/hooks.php at priority 1:

# Hook Point Scope Behavior
1 ClientAreaPrimaryNavbar Client Adds Cloudflare Connect (index.php?m=haikhavan_cloudflare_connect, icon fas fa-cloud, order 85) under the Domains navbar dropdown for logged-in clients.
2 ClientAreaPrimarySidebar Client On action=domaindetails, adds Manage Cloudflare (<Plan>) (with status badge) or Connect to Cloudflare (badge Free) at order 5 inside Domain Details Management.
3 ClientAreaFooterOutput Client Injects (a) a prominent Connect to Cloudflare / Cloudflare Connected banner card on clientareadomaindetails with 1-click inline AJAX onboarding (op=connect_domain), and (b) inline Connect to Cloudflare / Cloudflare (<Plan>) action buttons into #tableDomainsList on clientareadomains.
4 AdminClientDomainsTabFields Admin Adds a Cloudflare Connect row on Admin Client Domain details showing live Zone Status, Plan badge, Zone ID, assigned NS, and a direct button to action=domain_stats&id=<zone_id>.
5 AdminHomeWidgets Admin Registers an AbstractWidget (Cloudflare Security & Traffic Overview, 2 columns, weight 150) displaying 24h Zones, Requests, Bandwidth, Cache Hit %, Threats Blocked, and WAF Events across the fleet.
6 DailyCronJob Cron Iterates all rows in mod_hk_cf_zones, calls DomainConnector::syncZoneMetadata() (updating activation status, plan tier, NS) and refreshes 24h snapshots via AnalyticsService::getZoneAnalytics($z, '24h', true).

6. Plan-Tier Gating Matrix & Quotas

FeatureCatalog normalizes every Cloudflare plan (free, pro, business, enterprise) and enforces dual gating:

  1. Tier Requirement Check: FeatureCatalog::planMeetsRequirement($zonePlan, $requiredTier) against PLAN_ORDER (free=0 < pro=1 < business=2 < enterprise=3).
  2. Live Entitlement Check: Checks Cloudflare's editable boolean returned by GET /zones/{id}/settings. Both must pass for a control to unlock in the UI and pass server-side FeatureCatalog::validateMutation() (which returns HTTP 403 with locked: true on unauthorized mutations).

6.1 Plan Quotas (FeatureCatalog::getPlanQuotas())

Resource / Capability Free Pro Business Enterprise
Page Rules 3 20 50 125
Custom WAF Rules 5 20 100 1,000
Rate Limiting Rules 1 2 5 100
Redirect Rules 10 25 50 500
Cache Rules 10 25 50 500
Max Upload Size 100 MB 100 MB 200 MB 500 MB
Min Browser Cache TTL 1800s 3600s 1800s (120s option) 30s
Analytics Retention 30 days 30 days 30 days 90 days
Managed WAF & OWASP Locked Unlocked Unlocked Unlocked
Custom Error Pages Locked Unlocked Unlocked Unlocked
Purge by Tag / Host / Prefix Locked Locked Locked Unlocked
Logpush Streaming Locked Locked Locked Unlocked

6.2 Feature Catalog Tier Breakdown

Category Free Tier Features Pro Tier Features Business Tier Features Enterprise Tier Features
SSL / TLS SSL Mode (off/flexible/full/strict), Always Use HTTPS, Auto HTTPS Rewrites, Min TLS Version, TLS 1.3 (+ 0-RTT), Opportunistic Encryption, Authenticated Origin Pulls, HSTS, Universal SSL Packs — Custom Edge SSL Certificates Custom TLS Cipher Suites
Security & WAF Security Level (incl. Under Attack Mode), Challenge Passage TTL, Browser Integrity Check, Bot Fight Mode, Custom WAF Rules (5), IP Access Rules Managed WAF & OWASP Core Ruleset, Super Bot Fight Mode, Leaked Credential Detection Page Shield (Client-Side Script Protection) Enterprise Bot Management (ML Score & JA3/JA4), Advanced HTTP L7 DDoS Overrides, WAF log Action
Speed Brotli, Early Hints (HTTP 103), HTTP/2, HTTP/3 (QUIC), 0-RTT, Rocket Loader, Speed Brain Polish Image Optimization, WebP Conversion, Mirage, Enhanced HTTP/2 Prioritization, Argo Smart Routing — Prefetch URLs
Caching Caching Level, Browser Cache TTL (>=30m), Development Mode, Always Online, Crawler Hints, Argo Smart Tiered Cache, Purge Everything & Purge by URL (up to 30) — Short Browser Cache TTL (120s, 300s) Query String Sort, Ultra-short Browser Cache TTL (30s, 60s), Purge by Cache-Tag / Hostname / Prefix
Network IPv6, WebSockets, Pseudo IPv4, IP Geolocation, Onion Routing (Tor), gRPC, Max Upload (100 MB), CNAME Flattening (Apex) CNAME Flattening (flatten_all) Max Upload (125 / 150 / 200 MB) Max Upload (250 / 500 MB), True-Client-IP Header, Response Buffering
Scrape Shield & Logs Email Address Obfuscation, Server-Side Excludes (SSE), Hotlink Protection Custom Branded Error & Challenge Pages — Logpush (Real-Time Edge & WAF Log Streaming)

7. AJAX API Endpoints Reference

7.1 Client Area AJAX Router (index.php?m=haikhavan_cloudflare_connect&ajax=1)

Requires authenticated WHMCS client session ($_SESSION['uid']). Write operations require csrf_token (POST) or X-CF-CSRF header.

op Method CSRF Key Parameters Purpose
save_account POST Yes auth_type, credential, email Verify & encrypt client Cloudflare credentials
select_cf_account POST Yes cf_account_id Switch active Cloudflare account (multi-account tokens)
disconnect_account POST Yes — Remove stored client credentials
connect_domain POST Yes domainid, use_provider Full 6-step domain onboarding & NS registrar sync
sync_ns POST Yes domainid Re-push Cloudflare nameservers via localAPI('DomainUpdateNameservers')
verify_activation POST Yes domainid Call Cloudflare activation_check + live dns_get_record(..., DNS_NS)
disconnect_domain POST Yes domainid, delete_on_cloudflare Unlink zone from WHMCS (optionally delete zone on Cloudflare)
pause_zone POST Yes domainid, paused Toggle Cloudflare DNS-only pause state
load_zone_bundle GET No domainid Return synced zone metadata, evaluated catalog, quotas, certs, DNSSEC
update_feature POST Yes domainid, feature_id, value Plan-validated update of a zone setting or auxiliary API feature
dns_list GET No domainid List up to 200 DNS records for the zone
dns_create / dns_update POST Yes domainid, record_id, type, name, content, ttl, proxied, priority, comment Create or update a DNS record
dns_delete POST Yes domainid, record_id Delete a DNS record
dns_scan POST Yes domainid Trigger Cloudflare DNS record scan
dns_export GET No domainid Export zone in BIND format
dns_import POST Yes domainid, bind_content, proxied Upload BIND zone text to Cloudflare
dnssec_toggle POST Yes domainid, enabled Enable/disable DNSSEC and return DS record payload
purge_cache POST Yes domainid, mode (everything/files/advanced), files/tags/hosts/prefixes Execute cache purge (Enterprise-gated for advanced)
waf_custom_list GET No domainid List Custom WAF rules + plan quota
waf_custom_save / waf_custom_delete POST Yes domainid, description, expression, action, enabled / rule_id Save or delete Custom WAF rule (enforces plan rule limit & Enterprise log action)
ip_rules_list GET No domainid List IP/CIDR/ASN/Country access rules
ip_rules_create / ip_rules_delete POST Yes domainid, mode, target, value, notes / rule_id Create or delete IP Access Rule
page_rules_list GET No domainid List Page Rules + plan quota
page_rules_create / page_rules_delete POST Yes domainid, target_url, action_id, action_value, redirect_code / rule_id Create or delete Page Rule (enforces plan quota)
custom_pages_list GET No domainid List Custom Error Pages (requires Pro+)
logpush_list GET No domainid List Logpush Jobs (requires Enterprise)
analytics GET No domainid, timeframe, refresh Fetch zone GraphQL analytics (cached or force-refreshed)

7.2 Admin Area AJAX Router (admin/addonmodules.php?module=haikhavan_cloudflare_connect&ajax=1)

Requires authenticated WHMCS Admin session with module access permission.

op Method CSRF Key Parameters Purpose
save_provider_account POST Yes auth_type, credential, email Verify & save encrypted Provider Cloudflare account (userid=0)
disconnect_provider_account POST Yes — Delete Provider account row
sync_all POST Yes timeframe Force-sync metadata & analytics across all connected zones
sync_zone POST Yes zone_record_id, timeframe Force-sync single zone metadata & analytics
verify_zone POST Yes zone_record_id Trigger activation & live NS propagation check for a zone
sync_ns POST Yes zone_record_id Re-push assigned nameservers via WHMCS registrar API
domain_analytics GET No zone_record_id, timeframe, refresh Return single-zone analytics JSON
update_sandbox_plan POST Yes plan (free/pro/business/enterprise) Switch sandbox_plan and immediately update sandbox zones' plan tier

8. Troubleshooting Guide

Symptom Likely Cause Resolution
403 / Permission Denied on Analytics or WAF tab Scoped API Token is missing Zone Analytics:Read, Zone WAF:Edit, or Firewall Services:Edit. Re-create the token using the module's Create Pre-Filled Cloudflare API Token link (which pre-selects all 12 scopes).
Nameserver Sync shows manual_required The domain in WHMCS (tbldomains.registrar) has no registrar module assigned (empty or None). Assign a configured registrar module to the domain in WHMCS Admin, or copy the assigned Cloudflare NS into the external registrar manually.
Nameserver Sync shows failed Registrar module rejected localAPI('DomainUpdateNameservers') (e.g., domain locked, invalid credentials, or registrar API timeout). Inspect ns_sync_message on the domain's Overview tab or in Activity Audit Log, unlock the domain at the registrar, and click Auto-Push Nameservers to Registrar.
Activation check returns rate-limit notice Cloudflare rate-limits PUT /zones/{id}/activation_check to 1 request per hour on Free plans. Wait 60 minutes or let DailyCronJob / Cloudflare's automatic background poller transition the zone to active.
WAF raw events only show last 24 hours on 7D/30D view Expected Cloudflare platform limit: firewallEventsAdaptive raw logs are capped to 24h on Free/Pro plans. AnalyticsService::queryWafAnalytics() automatically clamps $rawSince to 24h while keeping aggregate charts (firewallEventsAdaptiveGroups) across the full selected timeframe.
"Stored Cloudflare credentials could not be decrypted" WHMCS $cc_encryption_hash in configuration.php was changed after credentials were saved. Reconnect the affected client or provider account to re-encrypt credentials under the active hash.
Sandbox data appearing in production sandbox_mode is still enabled in Addon Module settings. Navigate to System Settings -> Addon Modules -> Haikhavan Cloudflare Connect & Analytics -> Configure, uncheck Local Dev Sandbox / Demo Mode, and save.