---
title: REST API Reference
description: "TrustLens exposes a REST API for integrations. This page documents every endpoint with its request and response shape. The API is implemented in `includes/class-rest-api.php` and registered under the `trustlens/v1` namespace. Base URL: `https://yoursite.com/wp-json/trustlens/v1` --- ## Authentication Every endpoint requires authentication.…"
url: "https://webstepper.io/docs/trustlens/developer-documentation/rest-api-reference/"
updated: "2026-10-18"
category: Developer Documentation
---

# REST API Reference

TrustLens exposes a REST API for integrations. This page documents every endpoint with its request and response shape. The API is implemented in `includes/class-rest-api.php` and registered under the `trustlens/v1` namespace.

Base URL: `https://yoursite.com/wp-json/trustlens/v1`

---

## Authentication

Every endpoint requires authentication. The plugin accepts two mechanisms:

### Method 1 — WordPress User Authentication

Any authenticated WordPress user with the `manage_woocommerce` capability can call the API. The most common implementation is the WordPress application-password feature:

1. WordPress → Users → Edit your user
2. Scroll to **Application Passwords**
3. Add a new password (e.g. "TrustLens integration")
4. Use the username and generated password in HTTP Basic Auth

```
curl -u username:app_password 
  https://yoursite.com/wp-json/trustlens/v1/customers
```

Cookie-based authentication for browser requests also works as long as the logged-in user has `manage_woocommerce` and the request carries the standard WordPress REST nonce (`X-WP-Nonce`).

### Method 2 — TrustLens API Key

For integrations that don't have a WordPress user, TrustLens supports a static API key. The key is stored as a SHA-256 hash in the `trustlens_api_key` WordPress option and compared with `hash_equals()` for timing-safe matching.

Send the key in the `X-TrustLens-API-Key` request header:

```
curl -H "X-TrustLens-API-Key: your_api_key_here" 
  https://yoursite.com/wp-json/trustlens/v1/customers
```

Generate the key in **TrustLens → Settings → Integrations → REST API**. It's shown once — copy it then. **Regenerate** creates a new key and the old one stops working.

---

## The Eight Endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/customers` | List customers |
| GET | `/customers/lookup` | Look up a customer by raw email |
| GET | `/customers/{email_hash}` | Get customer record by hash |
| POST/PUT/PATCH | `/customers/{email_hash}` | Update customer state (block, allowlist) |
| GET | `/customers/{email_hash}/events` | List events on a customer's timeline |
| POST | `/customers/{email_hash}/recalculate` | Trigger immediate score recalculation |
| GET | `/stats` | Store-wide aggregate statistics |
| GET | `/stats/segments` | Segment distribution counts |

The `{email_hash}` parameter is the keyed HMAC-SHA256 hash of the customer's email (64 hex characters). Use `/customers/lookup?email=...` if you only have the raw email — you can't compute the hash yourself, because it's keyed with your site's secret salt.

---

## GET /customers

Paginated list of customers with optional filters.

### Query Parameters

| Param | Description |
| --- | --- |
| `page`, `per_page` | Pagination. `per_page` defaults to 20, maximum 100 |
| `segment` | Filter to one of: vip, trusted, normal, caution, risk, critical |
| `blocked` | Boolean — only blocked (`true`) or only unblocked (`false`) customers |
| `orderby`, `order` | Sort by `trust_score` (default), `total_orders`, `return_rate` or `created_at`; direction `ASC` (default) or `DESC` |

There are no score-range or allowlist filters. The response is a JSON array of customer objects (same shape as below) and includes `X-WP-Total` and `X-WP-TotalPages` headers in the standard WordPress REST convention.

---

## GET /customers/lookup

Look up a customer by raw email address. TrustLens hashes the email server-side and returns the matching customer record.

### Query Parameters

- `email` (required) — raw email address

Returns the same payload as `GET /customers/{email_hash}`.

---

## GET /customers/{email_hash}

Get the customer record.

### Response

```
{
  "id": 1234,
  "email_hash": "...",
  "trust_score": 75,
  "segment": "trusted",
  "segment_label": "Trusted",
  "total_orders": 12,
  "total_refunds": 1,
  "refunded_orders": 1,
  "return_rate": 8.3,
  "total_order_value": 1450.00,
  "total_refund_value": 89.00,
  "refund_amounts": {
    "amounts_by_currency": { "USD": 89.00 },
    "base_currency": "USD",
    "base_amount": 89.00,
    "normalization_complete": true
  },
  "is_blocked": false,
  "is_allowlisted": false,
  "is_flagged": false,
  "first_order_date": "2023-04-15 10:30:00",
  "last_order_date": "2024-03-10 14:22:00",
  "created_at": "2023-04-15 10:30:00",
  "updated_at": "2024-03-10 14:25:00"
}
```

The response doesn't include the email address, admin notes, tags, dispute or coupon counters. Returns `404` if the hash doesn't match any customer.

---

## POST/PUT/PATCH /customers/{email_hash}

Update mutable state on a customer record. The same endpoint is used for blocking and allowlisting — there are no separate `/block` or `/allowlist` endpoints.

### Updatable Fields

- `is_blocked` (boolean) — `true` blocks with the reason "Blocked via API"; `false` unblocks
- `is_allowlisted` (boolean)

Admin notes and tags can't be changed through the API. Other fields in the body are ignored.

### Example: Block a Customer

```
curl -X PATCH 
  -H "Content-Type: application/json" 
  -H "X-TrustLens-API-Key: ..." 
  -d '{"is_blocked": true}' 
  https://yoursite.com/wp-json/trustlens/v1/customers/{email_hash}
```

### Example: Allowlist a Customer

```
{"is_allowlisted": true}
```

Sending `"is_allowlisted": true` sets the score to 100 and the segment to VIP straight away and clears any block and review flag. Removing the allowlist (`false`) queues a recalculation that restores the score based on actual signals.

Both changes fire the same actions as the admin buttons (`trustlens/customer_blocked`, `trustlens/customer_allowlisted`, …), so automation rules and webhooks react to them. The response is the updated customer record; a `404` is returned for an unknown hash.

---

## GET /customers/{email_hash}/events

Returns the customer's event timeline, newest first — order placements, refunds, coupon applications, disputes, blocks, automation runs, etc.

### Query Parameters

- `page`, `per_page` — pagination (`per_page` defaults to 50, maximum 100)

There's no event-type or date filter; page through the results and filter client-side.

### Response Shape

```
[
  {
    "id": 12345,
    "event_type": "full_refund",
    "event_data": { ... },
    "order_id": 5432,
    "created_at": "2024-03-10 14:22:00"
  },
  ...
]
```

The response is a JSON array with `X-WP-Total` and `X-WP-TotalPages` headers. `event_data` is a JSON-decoded object whose shape depends on the event type; `order_id` is null for events without an order.

---

## POST /customers/{email_hash}/recalculate

Triggers an immediate, synchronous score recalculation and saves the result. It fires the same `trustlens/score_updated` (and, when the segment changes, `trustlens/segment_changed`) actions as an in-app recalculation.

### Response

The updated customer record — the same shape as `GET /customers/{email_hash}`, with the new `trust_score` and `segment`. The signal breakdown isn't included.

This is the only endpoint that runs scoring inline rather than queueing it via Action Scheduler.

---

## GET /stats

Aggregate store-wide statistics.

### Response

```
{
  "total_customers": 4823,
  "avg_trust_score": 64.2,
  "blocked_count": 47,
  "allowlisted_count": 89,
  "avg_return_rate": 8.4,
  "store_return_rate": 8.4,
  "customer_avg_return_rate": 11.7,
  "total_orders": 21950,
  "total_refunds": 1844
}
```

`store_return_rate` is refunded orders as a percentage of counted orders across the store; `avg_return_rate` carries the same value for backward compatibility; `customer_avg_return_rate` averages the per-customer rates of customers with orders. Useful for external dashboards and integrations that want a quick health snapshot.

---

## GET /stats/segments

Customer count per segment.

### Response

```
{
  "vip": 127,
  "trusted": 892,
  "normal": 3456,
  "caution": 234,
  "risk": 89,
  "critical": 25
}
```

---

## Error Format

Errors follow the WordPress REST convention:

```
{
  "code": "customer_not_found",
  "message": "Customer not found.",
  "data": { "status": 404 }
}
```

Common error codes:

- `403` — `rest_forbidden`: no user with `manage_woocommerce` and no valid API key
- `401` — WordPress itself rejected the credentials (e.g. a wrong application password)
- `404` — `customer_not_found`, or `rest_no_route` for a malformed hash
- `400` — `rest_invalid_param`: an invalid parameter (e.g. an unknown segment or a `per_page` over 100)

---

## Pagination Headers

List endpoints (`/customers`, `/customers/{hash}/events`) include WordPress's standard headers:

- `X-WP-Total` — total result count
- `X-WP-TotalPages` — total page count given the current `per_page`

---

## What This API Doesn't Do

To set expectations clearly:

- **No dispute endpoints.** Disputes are not exposed as a standalone resource through the REST API, and the customer payload doesn't include dispute counters. Dispute events appear in `/customers/{hash}/events`; use the WordPress admin or direct database queries for dispute-specific reads.
- **No health endpoint.** No unauthenticated probe endpoint is registered.
- **No automation rule management.** Automation rules are configured through the admin UI, not the REST API.
- **No webhook subscription management.** Outgoing webhooks are configured in the admin UI — per automation rule (Send Webhook action) or as global endpoints under Settings → Integrations → Webhooks.
- **No built-in rate limiting.** The plugin does not enforce request-rate limits at the application layer. If you need rate limiting, apply it at the web server, CDN, or reverse-proxy layer.

---

## Versioning

The namespace `trustlens/v1` is the current and only version. Future breaking changes would introduce `v2` while keeping `v1` available for backward compatibility. Non-breaking additions (new fields, new optional parameters) happen in `v1` without a version bump.

---

## Common Integration Patterns

- **Read customer score from CRM:** CRM calls `GET /customers/lookup?email=...` when displaying a customer record
- **Sync customer state to data warehouse:** page through `GET /customers` on a schedule, or receive TrustLens webhooks (per rule, or global endpoints) and ingest events
- **Help desk integration:** on ticket open, call `GET /customers/lookup?email={ticket.requester}` to surface trust context to the agent
- **External fraud-rule engine:** consume webhook events from your rules, apply external logic, call `PATCH /customers/{hash}` with `is_blocked: true` when needed
