Quick Installation
- Purchase the module and download
haikhavan_gateway_charges-ioncube-8.2-1.0.0-install.zipfrom your VPSrv Client Area Downloads. - Upload and extract the ZIP into your WHMCS root directory so files land in
modules/addons/haikhavan_gateway_charges/. - Verify PHP 8.2–8.4 with ionCube PHP Loader 14+ / 15.5+ is enabled on your server.
- Go to System Settings → Addon Modules in WHMCS Admin, click Activate next to Haikhavan Payment Gateway Charges & Smart Allocator, and assign administrator role access.
Module Slug: haikhavan_gateway_charges
Version: 1.0.0
Namespace: Haikhavan\GatewayCharges\
Target Runtime: WHMCS 9.1.2 · PHP 8.3 · MySQL 8.4
1. Architecture & File Inventory
modules/addons/haikhavan_gateway_charges/
├── whmcs.json # WHMCS schema 1.0 manifest
├── haikhavan_gateway_charges.php # Addon entry point (_config, _activate, _deactivate, _upgrade, _output, _clientarea)
├── hooks.php # 9 WHMCS hooks (InvoiceCreation, InvoiceChangeGateway, InvoicePaid, Checkout, Cart, ViewInvoice, Navbar, Footer, AdminHomeWidgets)
├── lib/
│ ├── Database.php # 6-table Capsule schema installer, active gateway discovery, currency & audit helpers
│ ├── FeeEngine.php # Rule matcher, Standard/Gross-Up/PayPalV2 math, idempotent invoice line-item manager, live simulator
│ ├── AllocatorEngine.php # Conditional Allow/Hide gateway router, safe fallback, telemetry logger, Rule Conflict Detector
│ ├── AnalyticsService.php # 14-day Fee Recovery vs. Discount ROI analytics & idempotent demo seeder
│ ├── AdminController.php # CSRF-guarded Admin SPA & AJAX CRUD / Simulator controller
│ └── ClientController.php # CSRF-guarded Client Billing Preferences, Live Calculator & Invoice Switcher controller
├── templates/
│ ├── admin/dashboard.php # 6-tab Admin Dashboard (ROI Analytics, Charge Rules, Allocator Rules, Live Simulator, Conflict Detector, Audit Log)
│ └── client/preferences.tpl # Smarty Client Area Payment Fees & Billing Preferences Portal
└── assets/
├── css/haikhavan_gateway_charges.css # Scoped zero-CDN fintech stylesheet (.hkgc-*)
└── js/haikhavan_gateway_charges.js # Zero-CDN High-DPI Canvas Dual-Bar & Donut chart engine + AJAX helper
2. Database Schema (mod_hk_gc_*)
2.1 mod_hk_gc_charge_rules
Per-gateway surcharge and discount rules evaluated in ascending (priority, id) order.
| Column | Type | Null | Default | Notes |
|---|---|---|---|---|
id |
INT UNSIGNED AI PK |
No | — | Primary key |
name |
VARCHAR(160) |
No | — | Admin rule label |
gateway |
VARCHAR(64) INDEX |
No | — | WHMCS gateway slug (stripe, paypal_ppcpv, banktransfer, etc.) |
rule_type |
VARCHAR(16) |
No | 'fee' |
fee | discount |
calc_method |
VARCHAR(20) |
No | 'standard' |
standard | gross_up | paypal_v2 |
fixed_amount |
DECIMAL(12,4) |
No | 0.0000 |
Fixed component |
percent_rate |
DECIMAL(8,4) |
No | 0.0000 |
Percentage rate (0–100) |
min_fee / max_fee |
DECIMAL(12,4) |
Yes | NULL |
Optional floor and cap bounds |
min_invoice_amount / max_invoice_amount |
DECIMAL(12,4) |
Yes | NULL |
Invoice subtotal eligibility tier |
taxable / apply_after_tax / apply_after_promo |
TINYINT |
No | 0/0/1 |
Tax and promo ordering controls |
line_item_label |
VARCHAR(191) |
Yes | NULL |
Custom invoice description template |
client_groups_json, excluded_clients_json, currencies_json, countries_json, products_json, billing_cycles_json |
TEXT |
Yes | NULL |
JSON string arrays for granular targeting |
charge_addfunds / charge_domains |
TINYINT |
No | 1 |
Toggle application to Add Funds and Domain items |
priority / enabled |
INT / TINYINT |
No | 10 / 1 |
Indexed evaluation order and active state |
2.2 mod_hk_gc_allocator_rules
Conditional checkout gateway visibility rules (action: allow | hide, client_status: any | first_time | returning, min_order_amount, max_order_amount, products_json, product_groups_json, client_groups_json, countries_json, currencies_json, billing_cycles_json, excluded_clients_json, priority, enabled).
2.3 mod_hk_gc_invoice_fees
Ledger tracking every applied, recalculated, removed, or paid gateway fee/discount line item (invoice_id, invoice_item_id, client_id, gateway, rule_id, rule_type, base_subtotal, fee_amount, currency_code, status, applied_at).
2.4 mod_hk_gc_client_prefs
Per-client billing preferences (client_id UNIQUE, preferred_gateway, prefer_discount_gateways, show_fee_breakdown).
2.5 mod_hk_gc_allocator_events & mod_hk_gc_audit_log
Checkout allocation telemetry (action_taken: allowed|hidden|blocked|fallback, country, currency_code, order_amount, context) and immutable operational audit trail.
3. Fee Calculation Math & Idempotent Invoice Engine
3.1 Calculation Modes (FeeEngine::calculateForRule)
Let $B = \text{subtotal} + (\text{apply_after_tax} ? \text{tax} : 0)$, $f = \text{fixed_amount}$, and $p = \text{percent_rate} / 100$:
- Standard / PayPal V2: $$\text{raw} = f + B \cdot p$$
- Gross-Up Merchant Recovery (
gross_up): Ensures that after the processor deducts $p%$ plus $f$ from the gross invoice amount, the merchant nets exactly $B$: $$\text{raw} = \frac{B + f}{1 - p} - B \qquad (0 < p < 0.99)$$ - Caps & Sign: Clamped by $[\text{min_fee}, \text{max_fee}]$, rounded half-up to 2 decimals (
PHP_ROUND_HALF_UP), negated fordiscountrules (never exceeding $B$).
3.2 Idempotent Gateway Switching (FeeEngine::applyToInvoice)
- Verifies invoice exists and
status === 'Unpaid'. - Deletes any prior
tblinvoiceitemsrows marked withtype = 'HkGatewayFee'and marks priormod_hk_gc_invoice_feesrows asrecalculated. - Recomputes clean base subtotal from all non-fee invoice items.
- Evaluates
FeeEngine::matchRule()for the new gateway. - If matched, inserts a single tagged
tblinvoiceitemsrow (type = 'HkGatewayFee',relid = rule_id), callsupdateInvoiceTotal($invoiceId)(with safe DB fallback), and logs the adjustment inmod_hk_gc_invoice_feesandmod_hk_gc_audit_log.
4. Smart Allocator & Rule Conflict Detector
4.1 Allocator Priority & Safe Fallback (AllocatorEngine::evaluateGateways)
- Rules are grouped per gateway and sorted by ascending
(priority, id). The first matching rule determinesallowvs.hide. client_status = 'first_time'evaluatestblinvoicescount wherestatus = 'Paid'equals0.- When
allocator_fallback_defaultis enabled and all candidate gateways would be hidden, all candidate gateways are safely restored and afallbacktelemetry event is recorded so checkout is never deadlocked.
4.2 Conflict Detector Checks (AllocatorEngine::detectConflicts)
CAP_INVERSION(critical):min_fee > max_feeon an active charge rule.HIGH_SURCHARGE(warning): Fee percentage exceeds 10% (compliance reminder).CHARGE_OVERLAP(warning): Multiple active charge rules on the same gateway overlap in amount range, currency, and country.ALLOCATOR_CONTRADICTION(warning): Overlappingallowandhideallocator rules target the same gateway.UNCONDITIONAL_HIDE_MASK(critical): An unconditionalhiderule completely masks a gateway that has active charge/discount rules.
5. WHMCS Hooks Inventory (hooks.php)
| Hook Point | Priority | Behavior |
|---|---|---|
InvoiceCreation |
1 |
Applies matching gateway fee/discount line item automatically upon invoice creation. |
InvoiceChangeGateway |
1 |
Cleanly strips previous gateway fee item and recalculates for the newly selected gateway. |
InvoicePaid |
1 |
Updates matching mod_hk_gc_invoice_fees rows to paid for realized ROI reporting. |
ShoppingCartValidateCheckout |
1 |
Blocks checkout submission if the chosen gateway violates an active Allocator hide rule. |
ClientAreaPageCart |
1 |
Filters $vars['gateways'] per Smart Allocator rules and injects hkgc_cart_preview. |
ClientAreaPageViewInvoice |
1 |
Computes live multi-gateway fee/discount comparison and injects native customAlert summary banner. |
ClientAreaPrimaryNavbar |
1 |
Adds Payment Fees & Preferences link under Billing dropdown. |
ClientAreaFooterOutput |
1 |
Renders interactive Live Fee & Discount Preview bar on Cart Checkout / Invoice pages. |
AdminHomeWidgets |
1 |
Displays live Fees Recovered, Discounts Given, Net Impact, Rule Counts, and Conflict Count on Admin Home. |
6. Security & Controller API
- CSRF Protection: All write operations in
AdminController(hkgc_admin_csrf/X-HK-GC-CSRF) andClientController(hkgc_client_csrf/X-HK-GC-CSRF) enforce timing-safehash_equals()validation and return HTTP403on failure. - Tenant Isolation:
ClientController::switch_invoice_gatewayverifiestblinvoices.userid === $_SESSION['uid']andstatus === 'Unpaid', plus validates gateway eligibility againstAllocatorEnginebefore applying changes. - Admin AJAX Ops:
seed_demo,simulate,save_charge_rule,clone_charge_rule,toggle_charge_rule,delete_charge_rule,save_allocator_rule,clone_allocator_rule,toggle_allocator_rule,delete_allocator_rule,recalculate_invoice. - Client AJAX Ops:
preview,save_preferences,switch_invoice_gateway.