Extending with Custom Modules
7 min read
- View as Markdown Open this page as plain Markdown (opens in a new tab)
- Open in ChatGPT Ask questions about this page (opens in a new tab)
- Open in Claude Ask questions about this page (opens in a new tab)
- Open in Google AI Studio Ask questions about this page (Google account required) (opens in a new tab)
The TrustLens detection module system is designed to be extensible. Beyond the eight built-in modules, developers can write their own modules that observe custom events, emit signals into the trust score, and respect the standard enable/disable option. This page walks through building a custom module from scratch.
The Module Interface #
Every module extends the abstract TrustLens_Module class (includes/class-module.php):
abstract class TrustLens_Module {
protected string $id = '';
protected string $name = '';
protected bool $is_pro = false;
public function register_hooks(): void {}
abstract public function get_signal( string $email_hash, ?object $customer = null ): array;
public function get_settings_fields(): array {
return array();
}
public function is_enabled(): bool {
// Pro modules also need an active license.
return (bool) get_option( "trustlens_module_{$this->id}_enabled", true );
}
protected function log_event( string $email_hash, string $event_type, array $data = array(), ?int $order_id = null ): void { ... }
protected function queue_score_update( string $email_hash, int $delay = 60 ): void { ... }
}
The required method:
get_signal( $email_hash, $customer )— return the module’s current signal contribution for a customer asarray( 'score' => int, 'reason' => string ), roughly −50 to +50.$customeris the customer row the score calculator already loaded (null when called directly)
Optional:
register_hooks()— wire the module into WordPress/WooCommerce events (the default does nothing, for modules that only contribute a signal)is_enabled()— override if you need custom enable logic
Because the base class declares typed properties and return types, your subclass must match them exactly — protected string $id, register_hooks(): void, and the full get_signal() signature — or PHP stops with a fatal error.
Example: Subscription Churn Risk Module #
Let’s build a custom module that flags customers as risky when they cancel subscriptions soon after signup. The full code:
<?php
/**
* Subscription Churn Risk Module
*
* Flags customers who cancel subscriptions within 30 days of signup.
*/
defined( 'ABSPATH' ) || exit;
class My_Module_Subscription_Churn extends TrustLens_Module {
protected string $id = 'subscription_churn';
protected string $name = 'Subscription Churn Risk';
public function register_hooks(): void {
add_action(
'woocommerce_subscription_status_cancelled',
array( $this, 'handle_cancellation' ),
10, 1
);
}
public function handle_cancellation( $subscription ) {
if ( ! $subscription ) {
return;
}
$start_date = $subscription->get_date( 'start' );
$cancelled_date = $subscription->get_date( 'cancelled' );
$days_active = ( strtotime( $cancelled_date ) - strtotime( $start_date ) ) / DAY_IN_SECONDS;
if ( $days_active > 30 ) {
return; // Not "early" cancellation
}
$email_hash = wstl_get_email_hash( $subscription->get_billing_email() );
if ( '' === $email_hash ) {
return;
}
// The events table is the canonical place for module-specific history;
// get_signal() counts these rows back. log_event() adds the module ID.
$this->log_event( $email_hash, 'subscription_early_cancel', array(
'subscription_id' => $subscription->get_id(),
'days_active' => (int) $days_active,
) );
// Queue a recalculation (deduplicated, runs about a minute later).
$this->queue_score_update( $email_hash );
}
public function get_signal( string $email_hash, ?object $customer = null ): array {
global $wpdb;
$count = (int) $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_events
WHERE email_hash = %s AND event_type = %s",
$email_hash,
'subscription_early_cancel'
) );
if ( $count >= 3 ) {
return array(
'score' => -20,
'reason' => sprintf( '%d subscription early cancellations', $count ),
);
}
if ( $count >= 2 ) {
return array(
'score' => -10,
'reason' => 'Multiple subscription early cancellations',
);
}
if ( $count === 1 ) {
return array(
'score' => -5,
'reason' => 'Subscription early cancellation',
);
}
return array( 'score' => 0, 'reason' => '' );
}
}
Registering the Module #
Hook into the trustlens/register_modules action:
add_action( 'trustlens/register_modules', function( $trustlens ) {
if ( ! class_exists( 'WC_Subscriptions' ) ) {
return; // Only register if Subscriptions is active
}
$trustlens->register_module( new My_Module_Subscription_Churn() );
} );
The action fires on WordPress init, after the built-in modules are registered and before any module’s hooks are wired, so add your listener earlier (e.g. at plugin load). After registration:
- It’s enabled by default — the option
trustlens_module_subscription_churn_enableddefaults to true. Custom modules don’t appear on the Settings → Detection tab, so to turn one off, set that option to false (e.g.wp option update trustlens_module_subscription_churn_enabled 0) - It contributes signals to customer scores (once the customer reaches the Full-confidence Order Threshold — below it only the Returns module runs, unless the
trustlens/skip_thin_data_scoringfilter says otherwise) - Its signals appear in customer profiles under its module ID
- Automation rules can’t reference it directly — the condition fields are a fixed list — but its effect on
trust_scoreandsegmentis visible to rules
Helper Functions Available #
| Function | Use |
|---|---|
wstl_get_email_hash($email) |
Compute the keyed HMAC-SHA256 hash for a customer email |
wstl_get_customer($email_hash) |
Get customer record object |
wstl_log_event($hash, $type, $data, $order_id = null) |
Append to event timeline (or $this->log_event() inside a module, which also records the module ID) |
wstl_queue_score_update($hash, $delay = 60) |
Queue async score recalculation (deduped) |
wstl_can_use_pro() |
Check whether Pro features are unlocked |
Storing Module-Specific Data #
Three options for storing data your module needs:
1. The Events Table (Recommended) #
Write module observations to {prefix}trustlens_events via wstl_log_event(). Read counts back at signal time with a simple SELECT COUNT(*). This pattern fits TrustLens’s existing append-only event model and benefits from the existing email_hash and event_type indexes.
2. WordPress Options (Lightweight Per-Store State) #
For settings or store-wide flags your module needs, use the WordPress options API: get_option() / update_option() with a my_module_* prefix.
3. Custom Table (Complex Multi-Row State) #
For complex per-customer data that doesn’t fit the events shape (e.g. composite aggregates), create your own table. Follow WordPress conventions: prefix with {wpdb->prefix}my_module_, use dbDelta() for creation.
There is no built-in per-customer meta table in TrustLens. The events table plus aggregate columns on trustlens_customers cover the patterns the core modules use; mirror that approach in your own modules.
Settings UI Integration #
The base class has a get_settings_fields() method, but nothing in the TrustLens admin renders it — custom modules get no settings section or toggle on the Detection tab. If your module needs settings, register your own options and settings page (or a section on an existing WordPress settings screen).
Reading a setting in your module:
$window_days = (int) get_option( 'my_module_subscription_churn_window', 30 );
Module Lifecycle #
- register_hooks(): Called once during
init, only if the module is enabled. Wire up your hooks here. - get_signal(): Called each time a customer’s score is recalculated, if the module is enabled. Read state, return signal.
Modules are reinstantiated on every page load (Action Scheduler workers, admin pages, REST requests). Don’t rely on instance state — store everything in the database.
Best Practices #
- Use the module ID consistently. It appears in signal logs, event data and the customer profile.
- Don’t fire score recalculations synchronously. Always use
wstl_queue_score_update(). - Handle missing dependencies gracefully. If your module relies on another plugin (Subscriptions, Memberships, etc.), check before registering.
- Don’t store raw PII. Use hashes consistent with TrustLens’s existing scheme.
- Respect the enabled option. TrustLens checks
is_enabled()before wiring hooks and collecting signals — don’t bypass it. - Use Action Scheduler for batch operations. Don’t loop over thousands of records synchronously.
Testing Your Module #
- Activate the plugin that registers the module (the module itself is enabled by default)
- Trigger a relevant event (e.g. cancel a test subscription)
- Verify the event appears in the customer’s Recent activity
- Wait 1–2 minutes for score recalculation (or click Recalculate on the profile)
- Open the customer’s profile and confirm the signal appears in the Signal impact panel
For automated testing, use the WordPress test suite with mock objects.
Distributing Your Module #
Custom modules can be:
- Single-purpose plugins (recommended) — separate plugin that depends on TrustLens being active
- Code in your theme’s
functions.php— fine for one-off store customizations - Mu-plugins — useful for required customizations across a site
If distributing publicly, follow WordPress plugin guidelines and declare dependency on TrustLens via the Requires Plugins header.
Examples of Custom Modules #
- Subscription churn (above)
- External fraud API integration — call an external service, factor result into score
- Loyalty program tier signal — boost score for active loyalty members
- B2B order velocity — different scoring for B2B vs B2C customers
- Promotion participation tracking — flag customers who only buy during sales
- Customer lifetime value scoring — explicit LTV signal
Updated on October 18, 2026