Skip to content

PHP examples

There is no PHP SDK: these files call LexOpti with PHP 8.1 or later and its curl extension, nothing else. Copy their functions into your application. LexOpti runs them, as written here, against the authorization server and the API in its tests (PHP 8.4), so they follow the API as it changes.

File What it does
oauth.php connects a member: authorization code with PKCE (S256), code exchange with HTTP Basic, access tokens refreshed with refresh token rotation, revocation
api.php calls /v1: a creation retried with its Idempotency-Key, a list read page by page, a problem read by its code and its request_id
integration.php every step of a complete integration: records linked by external_ref, checks and deep links, embed sessions, classification, cases, a page of clients kept in a cache, alerts reviewed, the case report checked against its sha256, the organization’s members, a sandbox trigger
firms.php the organization of a new customer, with your application’s own token (client credentials): created once for its manager to claim, read back, its claim link renewed
webhook.php the webhook endpoint: Standard Webhooks signature, timestamp, deduplication on the event id

Set LEXOPTI_CLIENT_ID, LEXOPTI_CLIENT_SECRET and LEXOPTI_REDIRECT_URI to your application’s, then run php oauth.php authorize, open the URL it prints, and pass the code and state of the callback to php oauth.php callback CODE STATE. php api.php then calls the API with the stored tokens, and php integration.php plays every step of an integration in your sandbox. Serve webhook.php as your endpoint, with its secret in LEXOPTI_WEBHOOK_SECRET (php -S 0.0.0.0:8080 webhook.php to try it).

The command line stands for your web application: keep the verifier and the state in the member’s session ($_SESSION), and the tokens in your database, one row per connected member, encrypted. Here they sit in files only their owner can read (created under umask(0077)), by default in the user’s own ~/.local/state/lexopti, never a shared temporary directory. Refresh tokens rotate: lexopti_access_token reads a valid token without any lock, refreshes under an exclusive lock, and stores the new refresh token before using the access token, so two PHP workers never refresh with the same token; with several servers, lock the member’s row in your database instead (SELECT … FOR UPDATE). A refresh that times out may have rotated the token on LexOpti’s side: it is sent again at once with the same refresh token, which LexOpti answers alike within 10 seconds (lifetimes and rotation).

oauth.php
<?php
declare(strict_types=1);
/*
* Connects a LexOpti member from a PHP server (PHP 8.1+, ext-curl): the
* authorization code with PKCE (S256), the code exchange, access tokens
* refreshed with refresh token rotation, and the revocation that
* disconnects the member. From the command line:
*
* php oauth.php authorize prints the URL to send the member to
* php oauth.php callback CODE STATE checks the state, exchanges the code
* php oauth.php token prints a valid access token
* php oauth.php refresh refreshes now, prints the new token
* php oauth.php revoke disconnects the member
*
* Environment: LEXOPTI_CLIENT_ID, LEXOPTI_CLIENT_SECRET, LEXOPTI_REDIRECT_URI,
* LEXOPTI_TOKEN_FILE (where the tokens are kept, by default in the user's
* own ~/.local/state/lexopti, never a shared temporary directory) and
* LEXOPTI_URL (LexOpti, https://app.lexopti.com by default). In a web
* application, keep the verifier and the state in the member's session,
* and the tokens in your database, encrypted, one row per connected member;
* with several servers, lock that row (SELECT … FOR UPDATE) where this file
* takes its flock.
*/
/** @return array{url: string, resource: string, client_id: string, client_secret: string, redirect_uri: string, token_file: string} */
function lexopti_config(): array
{
$url = rtrim(getenv('LEXOPTI_URL') ?: 'https://app.lexopti.com', '/');
$state = getenv('XDG_STATE_HOME') ?: rtrim((string) getenv('HOME'), '/') . '/.local/state';
return [
'url' => $url,
'resource' => $url . '/v1',
'client_id' => (string) getenv('LEXOPTI_CLIENT_ID'),
'client_secret' => (string) getenv('LEXOPTI_CLIENT_SECRET'),
'redirect_uri' => getenv('LEXOPTI_REDIRECT_URI') ?: 'https://crm.example.com/oauth/callback',
'token_file' => getenv('LEXOPTI_TOKEN_FILE') ?: $state . '/lexopti/tokens.json',
];
}
/** LexOpti did not answer: a request may still have reached it. */
final class LexOptiUnreachable extends RuntimeException
{
}
/**
* Writes a file only its owner can read, atomically: the umask makes it
* 0600 from its creation (no window where another user could open it), and
* a crash never leaves half a file.
*/
function lexopti_write_private(string $path, string $contents): void
{
$previous = umask(0077);
try {
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0700, true) && !is_dir(dirname($path))) {
throw new RuntimeException('Cannot create ' . dirname($path));
}
$temporary = $path . '.' . bin2hex(random_bytes(8));
if (file_put_contents($temporary, $contents) === false || !rename($temporary, $path)) {
throw new RuntimeException("Cannot write {$path}");
}
} finally {
umask($previous);
}
}
function base64url(string $bytes): string
{
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}
/**
* The hint of a member's sign-up (`lexopti_hint`): what your records know
* of them (email, given_name, family_name, firm.name, firm.siren,
* firm.profession, firm.phone, firm.address), shown first on LexOpti's
* sign-up form and never taken for proven. Base64url of the JSON, 2 KB at
* most; an invalid field drops the whole hint, never the sign-in.
*/
function lexopti_partner_hint(array $hint): string
{
return base64url(json_encode($hint, JSON_THROW_ON_ERROR));
}
/**
* The URL to send the member to, and what to keep in their session until
* the callback: the PKCE verifier and the state. `$hint`: the sign-up hint
* of a member your records already know (lexopti_partner_hint).
*
* @return array{url: string, verifier: string, state: string}
*/
function lexopti_authorization(array $config, ?array $hint = null): array
{
$verifier = base64url(random_bytes(32));
$state = base64url(random_bytes(16));
$params = [
'client_id' => $config['client_id'],
'code_challenge' => base64url(hash('sha256', $verifier, true)),
'code_challenge_method' => 'S256',
'redirect_uri' => $config['redirect_uri'],
'resource' => $config['resource'],
'response_type' => 'code',
'scope' => 'openid email offline_access lexopti:read lexopti:write',
'state' => $state,
];
// The hint rides the authorization URL, beside the OAuth parameters.
if ($hint !== null) {
$params['lexopti_hint'] = lexopti_partner_hint($hint);
}
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
return [
'url' => $config['url'] . '/api/auth/oauth2/authorize?' . $query,
'verifier' => $verifier,
'state' => $state,
];
}
/**
* A grant at the token endpoint, the client authenticated with HTTP Basic
* (client_secret_basic): the tokens, with the time the access token expires.
*/
function lexopti_token_request(array $config, array $grant): array
{
$credentials = rawurlencode($config['client_id']) . ':' . rawurlencode($config['client_secret']);
$curl = curl_init($config['url'] . '/api/auth/oauth2/token');
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($grant + ['resource' => $config['resource']]),
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode($credentials),
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$body = curl_exec($curl);
if (!is_string($body)) {
throw new LexOptiUnreachable('LexOpti is unreachable: ' . curl_error($curl));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$tokens = json_decode($body, true);
if ($status !== 200 || !is_array($tokens) || !isset($tokens['access_token'])) {
// invalid_grant on a refresh: the member must authorize again.
$error = is_array($tokens) ? ($tokens['error'] ?? 'unknown') : 'unknown';
throw new RuntimeException("The token endpoint answered {$status} ({$error})");
}
return $tokens + ['expires_at' => time() + (int) $tokens['expires_in']];
}
/** Writes the tokens, readable by their owner only. */
function lexopti_save_tokens(array $config, array $tokens): void
{
lexopti_write_private($config['token_file'], json_encode($tokens, JSON_THROW_ON_ERROR));
}
function lexopti_read_tokens(array $config): array
{
return json_decode((string) file_get_contents($config['token_file']), true, 512, JSON_THROW_ON_ERROR);
}
/**
* The callback: the state must be the one kept in the member's session,
* then the code is exchanged with its verifier, once.
*/
function lexopti_callback(array $config, array $session, string $code, string $state): array
{
if (!hash_equals($session['state'], $state)) {
throw new RuntimeException('The state is not this session\'s.');
}
$tokens = lexopti_token_request($config, [
'grant_type' => 'authorization_code',
'code' => $code,
'code_verifier' => $session['verifier'],
'redirect_uri' => $config['redirect_uri'],
]);
lexopti_save_tokens($config, $tokens);
return $tokens;
}
/**
* A valid access token, refreshed when it expires within a minute (or now,
* with $force). A valid token is read without any lock. Refresh tokens
* rotate: every refresh answers a new one and the old one stops working, so
* a refresh runs under an exclusive lock, reads the tokens again (another
* worker may have refreshed meanwhile), and stores the new refresh token
* before anything uses it.
*
* A refresh that times out may have been answered: LexOpti then rotated the
* token and the new one is lost. It is sent again at once, with the same
* refresh token: within 10 seconds LexOpti answers the same tokens again.
* Later, the old token is treated as stolen and the member must authorize
* again.
*/
function lexopti_access_token(array $config, bool $force = false): string
{
$tokens = lexopti_read_tokens($config);
if (!$force && $tokens['expires_at'] - 60 > time()) {
return $tokens['access_token'];
}
$lock = fopen($config['token_file'] . '.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX)) {
throw new RuntimeException('Cannot lock the token file.');
}
try {
$current = lexopti_read_tokens($config);
if ($current['refresh_token'] !== $tokens['refresh_token']) {
return $current['access_token'];
}
$grant = ['grant_type' => 'refresh_token', 'refresh_token' => $current['refresh_token']];
try {
$refreshed = lexopti_token_request($config, $grant);
} catch (LexOptiUnreachable $lost) {
$refreshed = lexopti_token_request($config, $grant);
}
// An answer without a refresh token keeps the current one.
$refreshed += ['refresh_token' => $current['refresh_token']];
lexopti_save_tokens($config, $refreshed);
return $refreshed['access_token'];
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
/**
* Disconnects the member at the revocation endpoint (RFC 7009), with HTTP
* Basic: first the refresh token, which ends the grant, then the access
* token. The tokens are dropped even if a revocation fails.
*/
function lexopti_revoke(array $config): void
{
$tokens = lexopti_read_tokens($config);
$credentials = rawurlencode($config['client_id']) . ':' . rawurlencode($config['client_secret']);
foreach (['refresh_token', 'access_token'] as $hint) {
$curl = curl_init($config['url'] . '/api/auth/oauth2/revoke');
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(['token' => $tokens[$hint], 'token_type_hint' => $hint]),
CURLOPT_HTTPHEADER => ['Authorization: Basic ' . base64_encode($credentials)],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
curl_exec($curl);
}
unlink($config['token_file']);
}
if (PHP_SAPI === 'cli' && realpath($argv[0] ?? '') === __FILE__) {
$config = lexopti_config();
// Stands for the member's session ($_SESSION) between the two steps.
$sessionFile = $config['token_file'] . '.session';
switch ($argv[1] ?? '') {
case 'authorize':
$authorization = lexopti_authorization($config);
lexopti_write_private($sessionFile, json_encode($authorization, JSON_THROW_ON_ERROR));
echo $authorization['url'], PHP_EOL;
break;
case 'callback':
$session = json_decode((string) file_get_contents($sessionFile), true, 512, JSON_THROW_ON_ERROR);
try {
lexopti_callback($config, $session, $argv[2] ?? '', $argv[3] ?? '');
} catch (RuntimeException $refused) {
fwrite(STDERR, $refused->getMessage() . PHP_EOL);
exit(1);
}
unlink($sessionFile);
echo 'connected', PHP_EOL;
break;
case 'token':
case 'refresh':
echo lexopti_access_token($config, $argv[1] === 'refresh'), PHP_EOL;
break;
case 'revoke':
lexopti_revoke($config);
echo 'disconnected', PHP_EOL;
break;
default:
fwrite(STDERR, "usage: php oauth.php authorize | callback CODE STATE | token | refresh | revoke\n");
exit(2);
}
}

Every creation sends an Idempotency-Key, one per creation intent, kept across its retries: a retry gets the first answer instead of a second client (idempotency). Lists page with next_cursor (pagination). Log a problem’s request_id, and quote it to LexOpti support (request ids).

api.php
<?php
declare(strict_types=1);
/*
* Calls the LexOpti API from PHP (PHP 8.1+, ext-curl), with the tokens
* oauth.php keeps: a client created with an Idempotency-Key and retried
* safely, every client read page by page, and a problem read by its code
* and its request id. Run `php api.php` once a member is connected.
*/
require_once __DIR__ . '/oauth.php';
/** A failed call: the problem details (RFC 9457) LexOpti answered. */
final class LexOptiProblem extends RuntimeException
{
public function __construct(
public readonly int $status,
/** Stable, in English: branch on it, never on the message. */
public readonly string $problemCode,
/** Quote it to LexOpti support (the Request-Id header). */
public readonly string $requestId,
string $detail,
) {
parent::__construct($detail, $status);
}
}
/** A random UUID (version 4), for an Idempotency-Key. */
function uuid_v4(): string
{
$bytes = random_bytes(16);
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
/**
* One call to /v1, its JSON answer decoded. Retried up to three times after
* a 429 (waiting Retry-After) and, for a GET or a call with its
* Idempotency-Key, after a 5xx or a network failure: the same key gets the
* first answer, so a POST that did run is never run twice. A 401 gets one
* retry with a refreshed token.
*/
function lexopti_request(array $config, string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
$refresh = false;
for ($attempt = 0; ; $attempt++) {
$headers = [];
$curl = curl_init($config['url'] . $path);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => array_values(array_filter([
'Authorization: Bearer ' . lexopti_access_token($config, $refresh),
'Accept: application/json',
'Accept-Language: fr',
$body === null ? null : 'Content-Type: application/json',
$idempotencyKey === null ? null : 'Idempotency-Key: ' . $idempotencyKey,
])),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($body !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
}
$answer = curl_exec($curl);
$status = is_string($answer) ? curl_getinfo($curl, CURLINFO_RESPONSE_CODE) : 0;
// A token revoked or expired early: refresh it once, then retry. A 401
// and a 429 are answered before anything runs; a failure may come
// after, so only a GET or a call with its key is sent again then.
$refresh = $status === 401 && !$refresh;
$replayable = $method === 'GET' || $idempotencyKey !== null;
$failed = $status === 0 || $status >= 500;
if (($refresh || $status === 429 || ($failed && $replayable)) && $attempt < 3) {
$wait = isset($headers['retry-after']) ? (int) $headers['retry-after'] : 2 ** $attempt;
sleep($refresh ? 0 : min($wait, 60));
continue;
}
if ($status === 0) {
throw new RuntimeException('LexOpti is unreachable: ' . curl_error($curl));
}
$decoded = $answer === '' ? [] : json_decode($answer, true);
if ($status >= 400) {
// A proxy's HTML page, a cut answer: a problem all the same.
$problem = is_array($decoded) ? $decoded : [];
throw new LexOptiProblem(
$status,
$problem['code'] ?? 'unknown',
$problem['request_id'] ?? ($headers['request-id'] ?? ''),
$problem['detail'] ?? 'LexOpti answered ' . $status . ' without problem details.',
);
}
if (!is_array($decoded)) {
throw new RuntimeException("LexOpti answered {$status} with a body that is not JSON.");
}
return $decoded;
}
}
/**
* Every item of a list, page by page: `next_cursor` is passed as `cursor`
* while `has_more` is true.
*/
function lexopti_list_all(array $config, string $path, array $query = [], int $limit = 100): Generator
{
$cursor = null;
do {
$page = lexopti_request($config, 'GET', $path . '?' . http_build_query($query + array_filter([
'limit' => $limit,
'cursor' => $cursor,
])));
yield from $page['data'];
$cursor = $page['next_cursor'];
} while ($page['has_more']);
}
if (PHP_SAPI === 'cli' && realpath($argv[0] ?? '') === __FILE__) {
$config = lexopti_config();
// One key per creation intent, kept with it: a retry sends the same key
// and body, and gets the first answer instead of a second client.
$key = uuid_v4();
$person = ['type' => 'person', 'person' => ['first_name' => 'Camille', 'last_name' => 'Durand']];
$created = lexopti_request($config, 'POST', '/v1/clients', $person, $key);
$retried = lexopti_request($config, 'POST', '/v1/clients', $person, $key);
echo 'created ', $created['id'], PHP_EOL, 'retried ', $retried['id'], PHP_EOL;
$count = 0;
foreach (lexopti_list_all($config, '/v1/clients', [], (int) (getenv('LEXOPTI_PAGE_SIZE') ?: 100)) as $client) {
$count++;
}
echo 'listed ', $count, PHP_EOL;
try {
lexopti_request($config, 'GET', '/v1/clients/' . uuid_v4());
} catch (LexOptiProblem $problem) {
// Log the request id with the code: support finds the request by it.
echo $problem->problemCode, ' ', $problem->requestId, PHP_EOL;
}
}

The functions the complete integration shows in PHP, on lexopti_request and lexopti_list_all: each mirrors the TypeScript of its step. Its command line plays them in a row in your sandbox; LEXOPTI_SANDBOX_CLIENT, LEXOPTI_SANDBOX_CASE and LEXOPTI_CODE_CHALLENGE name a client, a case and an embedded component’s challenge.

integration.php
<?php
declare(strict_types=1);
/*
* The steps of a complete integration in PHP (PHP 8.1+, ext-curl), on the
* calls of api.php and the tokens of oauth.php: your records linked to
* LexOpti clients, checks and deep links, embed sessions, and what your
* own screens read (classification, cases, a page of clients kept in a
* cache, alerts to review, the case report, the organization's members, the
* preliminary screening). Run `php integration.php` once a member is
* connected: it plays each step in the member's sandbox.
*/
require_once __DIR__ . '/api.php';
/** The LexOpti client of your contact: the one its reference names, or a new one. */
function lexopti_link_contact(array $config, string $contactId): string
{
$externalRef = 'crm:contact:' . $contactId;
$lookup = '/v1/clients?' . http_build_query(['external_ref' => $externalRef]);
$found = lexopti_request($config, 'GET', $lookup);
if (isset($found['data'][0])) {
return $found['data'][0]['id'];
}
try {
$client = lexopti_request($config, 'POST', '/v1/clients', [
'type' => 'person',
'person' => [
'first_name' => 'Camille',
'last_name' => 'Durand',
'birth_date' => '1984-03-12',
'nationalities' => ['FR'],
],
'external_ref' => $externalRef,
], uuid_v4());
return $client['id'];
} catch (LexOptiProblem $problem) {
// Another request linked the reference meanwhile: nothing was created.
if ($problem->problemCode !== 'external_ref_conflict') {
throw $problem;
}
$winner = lexopti_request($config, 'GET', $lookup);
if (!isset($winner['data'][0])) {
throw $problem;
}
return $winner['data'][0]['id'];
}
}
/**
* Launches a check of the client, and a link that opens the client in
* LexOpti, for the signed-in member.
*
* @return array{check: array, link: array}
*/
function lexopti_check_and_link(array $config, string $clientId): array
{
$check = lexopti_request($config, 'POST', '/v1/checks', ['client_id' => $clientId], uuid_v4());
$link = lexopti_request($config, 'POST', '/v1/deep-links', ['client_id' => $clientId]);
return ['check' => $check, 'link' => $link];
}
/**
* The one-time code of an embedded component, for the challenge and the
* component the element passed to its sessionProvider, as is. Answer
* ['code' => …] to the page; never cache it (60 seconds, single use).
*/
function lexopti_embed_session(array $config, string $codeChallenge, string $component): string
{
$session = lexopti_request($config, 'POST', '/v1/embed-sessions', [
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
'component' => $component,
'origin' => 'https://crm.example.com',
]);
return $session['code'];
}
/**
* Where a client's classification stands: its level once validated,
* otherwise the questions left for the member to answer, in LexOpti.
*/
function lexopti_classification_summary(array $config, string $clientId): string
{
$classification = lexopti_request($config, 'GET', '/v1/clients/' . rawurlencode($clientId) . '/classification');
if ($classification['state'] === 'validated') {
return "{$classification['level']} {$classification['validated_at']}";
}
return 'to answer: ' . implode(', ', $classification['missing_answers']['question_ids']);
}
/** The cases of a client, main or not, newest first, each with its parties. */
function lexopti_client_cases(array $config, string $clientId): array
{
$page = lexopti_request($config, 'GET', '/v1/cases?' . http_build_query(['client_id' => $clientId]));
return array_map(fn (array $case): array => [
'label' => $case['label'],
'risk_level' => $case['risk_level'],
'classification_state' => $case['classification_state'],
'pending_alert_count' => $case['pending_alert_count'],
'parties' => array_map(fn (array $party): string => "{$party['name']} ({$party['role']})", $case['parties']),
], $page['data']);
}
/** What your screens show of each client, as `expand[]` adds it. */
const LEXOPTI_EXPAND = ['last_check', 'open_alerts_count', 'classification_state', 'cases'];
/** Up to 100 clients in one request, by their LexOpti ids, every expansion in it. */
function lexopti_read_clients(array $config, array $clientIds): array
{
$query = http_build_query(['ids' => implode(',', $clientIds), 'limit' => 100]);
foreach (LEXOPTI_EXPAND as $field) {
$query .= '&expand[]=' . $field;
}
$page = lexopti_request($config, 'GET', '/v1/clients?' . $query);
return array_column($page['data'], null, 'id');
}
/**
* On a webhook naming a client: that record alone in the cache, then
* redraw it; deleted, or no longer this organization's, out of the cache.
*/
function lexopti_refresh_client(array $config, array &$cache, string $clientId): void
{
$client = lexopti_read_clients($config, [$clientId])[$clientId] ?? null;
if ($client === null) {
unset($cache[$clientId]);
} else {
$cache[$clientId] = $client;
}
}
/** The alerts of a client waiting for a member's review. */
function lexopti_pending_alerts(array $config, string $clientId): array
{
$query = http_build_query(['client_id' => $clientId, 'status' => 'pending']);
return lexopti_request($config, 'GET', '/v1/alerts?' . $query)['data'];
}
/** Records the member's decision on an alert, typed in your screen. */
function lexopti_review_alert(array $config, string $alertId, string $status, string $notes): array
{
return lexopti_request($config, 'PATCH', '/v1/alerts/' . rawurlencode($alertId), [
'status' => $status,
'notes' => $notes,
]);
}
/**
* The report of a case for partners, downloaded and checked against its
* sha256: answer it to the member as application/pdf. No token for the
* signed URL: it is the credential, for 5 minutes.
*/
function lexopti_case_report(array $config, string $caseId): string
{
$report = lexopti_request($config, 'GET', '/v1/cases/' . rawurlencode($caseId) . '/report');
$curl = curl_init($report['download_url']);
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
$file = curl_exec($curl);
if (!is_string($file) || !hash_equals($report['sha256'], hash('sha256', $file))) {
throw new RuntimeException('The report is not the file LexOpti announced.');
}
return $file;
}
/** The organization's members by e-mail, once your application is installed for it. */
function lexopti_member_ids_by_email(array $config): array
{
$memberIds = [];
foreach (lexopti_list_all($config, '/v1/members') as $member) {
$memberIds[strtolower($member['email'])] = $member['id'];
}
return $memberIds;
}
/** In a sandbox, a new vigilance alert on a client, to test your webhooks. */
function lexopti_sandbox_alert(array $config, string $clientId): array
{
return lexopti_request($config, 'POST', '/v1/sandbox/triggers', [
'type' => 'vigilance_alert',
'client_id' => $clientId,
]);
}
/**
* A client's preliminary screening as your screen words it: the status of
* its latest request, then its current result (the latest completed
* search, never hidden by a newer pending request): the outcome, the lists
* searched with the source statement their licence asks you to show, and
* the possible matches (probable namesakes left aside). Null when it has
* none.
*/
function lexopti_preliminary_screening(array $config, string $clientId): ?array
{
try {
$screening = lexopti_request($config, 'GET', '/v1/clients/' . rawurlencode($clientId) . '/preliminary-screening');
} catch (LexOptiProblem $problem) {
if ($problem->problemCode === 'not_found') {
return null;
}
throw $problem;
}
$current = $screening['current'];
return [
'status' => $screening['latest']['status'],
'outcome' => $current['outcome'] ?? null,
'checked_at' => $current['checked_at'] ?? null,
'lists' => array_map(fn (array $list): string => $list['attribution'], $current['lists'] ?? []),
'matches' => array_values(array_filter($current['matches'] ?? [], fn (array $match): bool => !$match['homonym'])),
];
}
/**
* Asks LexOpti for the free preliminary screening of a client your software
* did not create through the API (one created in LexOpti and linked, or
* whose identity changed elsewhere): the clients your software creates are
* screened by LexOpti itself. 202 with the screening and its new pending request; a
* request already running (409 preliminary_screening_pending) needs no
* other, and a deployment without the feature (503) is told as such.
*/
function lexopti_request_preliminary_screening(array $config, string $clientId): ?array
{
try {
return lexopti_request($config, 'POST', '/v1/clients/' . rawurlencode($clientId) . '/preliminary-screening', null, uuid_v4());
} catch (LexOptiProblem $problem) {
if (in_array($problem->problemCode, ['preliminary_screening_pending', 'preliminary_screening_unavailable'], true)) {
return null;
}
throw $problem;
}
}
/**
* The case of a matter of your software, as POST /v1/cases and its preview
* take it: the client by your reference, a party with its role, the
* matter's own id.
*/
function lexopti_matter_case(string $matterId, string $contactId, array $seller): array
{
return [
'clients' => [['external_ref' => "crm:contact:{$contactId}"]],
'types' => ['vente_immobiliere'],
'parties' => [$seller],
'external_ref' => "crm:matter:{$matterId}",
];
}
/** What creating the case costs, to show the member before they confirm. */
function lexopti_preview_case(array $config, array $case): array
{
return lexopti_request($config, 'POST', '/v1/cases/preview', $case);
}
/** Once the member confirmed the cost: one case per matter, whatever the retries. */
function lexopti_create_case(array $config, string $matterId, array $case): array
{
return lexopti_request($config, 'POST', '/v1/cases', $case, "crm-matter-{$matterId}");
}
if (PHP_SAPI === 'cli' && realpath($argv[0] ?? '') === __FILE__) {
$config = lexopti_config();
$clientId = lexopti_link_contact($config, '1042');
echo 'linked ', $clientId, ' ', lexopti_link_contact($config, '1042'), PHP_EOL;
$screened = lexopti_check_and_link($config, $clientId);
echo 'checked ', $screened['check']['client_id'], ' ', $screened['link']['url'], PHP_EOL;
$code = lexopti_embed_session($config, (string) getenv('LEXOPTI_CODE_CHALLENGE'), 'client');
echo 'embed ', $code, PHP_EOL;
// The sandbox's own client, its case and its pending alert.
$sandboxClient = (string) getenv('LEXOPTI_SANDBOX_CLIENT');
echo 'classification ', lexopti_classification_summary($config, $sandboxClient), PHP_EOL;
echo 'cases ', json_encode(lexopti_client_cases($config, $sandboxClient), JSON_THROW_ON_ERROR), PHP_EOL;
$cache = lexopti_read_clients($config, [$sandboxClient, $clientId]);
lexopti_refresh_client($config, $cache, $sandboxClient);
$cache['gone-client'] = $cache[$sandboxClient];
lexopti_refresh_client($config, $cache, 'gone-client');
$client = $cache[$sandboxClient];
echo 'cache ', implode(',', array_keys($cache)), ' ', $client['open_alerts_count'], ' ',
$client['classification_state'], ' ', count($client['cases']['data']), PHP_EOL;
foreach (lexopti_pending_alerts($config, $sandboxClient) as $alert) {
$reviewed = lexopti_review_alert($config, $alert['id'], 'dismissed', 'Homonym: different date of birth.');
echo 'reviewed ', $reviewed['id'], ' ', $reviewed['status'], PHP_EOL;
}
echo 'report ', hash('sha256', lexopti_case_report($config, (string) getenv('LEXOPTI_SANDBOX_CASE'))), PHP_EOL;
echo 'members ', implode(',', lexopti_member_ids_by_email($config)), PHP_EOL;
// The sandbox client's free preliminary screening, then the new client's,
// which LexOpti ran itself when your software created it.
$preliminary = lexopti_preliminary_screening($config, $sandboxClient);
$created = lexopti_preliminary_screening($config, $clientId);
echo 'preliminary ', $preliminary['status'], ' ', $preliminary['outcome'], ' ', count($preliminary['lists']), ' ',
count($preliminary['matches']), ' ', $created['status'] ?? 'none', PHP_EOL;
echo 'triggered ', implode(',', lexopti_sandbox_alert($config, $sandboxClient)['events']), PHP_EOL;
// The matter of contact 1042, its seller a party: priced, then created once.
$case = lexopti_matter_case('7', '1042', [
'type' => 'company',
'role' => 'vendeur',
'company' => ['name' => 'SCI Horizon', 'siren' => '552100554'],
]);
$preview = lexopti_preview_case($config, $case);
$created = lexopti_create_case($config, '7', $case);
$retried = lexopti_create_case($config, '7', $case);
echo 'case ', $preview['credits']['needed'], ' ', $created['id'], ' ', $retried['id'], ' ',
$created['credits_charged'], ' ', $created['external_ref'], PHP_EOL;
}

With your application’s own token (client credentials, scope lexopti:firms), never a member’s: php firms.php prepares the organization of customer 12 (a firm) for its manager to claim, once whatever the retries, and reads it back; php firms.php renew FIRM_ID renews its link, once a minute at most. LexOpti e-mails the claim link to the manager (create the organization of a new customer). Only an application approved for production gets this token.

firms.php
<?php
declare(strict_types=1);
/*
* Creates the firm of a new customer for its manager to claim (PHP 8.1+,
* ext-curl), with your application's own token: client credentials, scope
* lexopti:firms, no member behind it. LexOpti e-mails the claim link to the
* manager. Run `php firms.php` with LEXOPTI_CLIENT_ID and
* LEXOPTI_CLIENT_SECRET: it creates the firm of customer 12 and reads it back;
* `php firms.php renew FIRM_ID` renews its link (once a minute at most).
*/
require_once __DIR__ . '/api.php';
/** Your application's own token (client credentials): 15 minutes, no refresh token. */
function lexopti_application_token(array $config): string
{
return lexopti_token_request($config, [
'grant_type' => 'client_credentials',
'scope' => 'lexopti:firms',
])['access_token'];
}
/** One call to /v1/firms with the application's token, its JSON answer decoded. */
function lexopti_firms_request(array $config, string $token, string $method, string $path, ?string $idempotencyKey = null, ?array $body = null): array
{
$headers = [];
$curl = curl_init($config['url'] . $path);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => array_values(array_filter([
'Authorization: Bearer ' . $token,
'Accept: application/json',
$body === null ? null : 'Content-Type: application/json',
$idempotencyKey === null ? null : 'Idempotency-Key: ' . $idempotencyKey,
])),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($body !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
}
$answer = curl_exec($curl);
if (!is_string($answer)) {
throw new LexOptiUnreachable('LexOpti is unreachable: ' . curl_error($curl));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$decoded = json_decode($answer, true);
if ($status >= 400) {
$problem = is_array($decoded) ? $decoded : [];
throw new LexOptiProblem(
$status,
$problem['code'] ?? 'unknown',
$problem['request_id'] ?? ($headers['request-id'] ?? ''),
$problem['detail'] ?? 'LexOpti answered ' . $status . ' without problem details.',
);
}
if (!is_array($decoded)) {
throw new RuntimeException("LexOpti answered {$status} with a body that is not JSON.");
}
return $decoded;
}
/**
* The firm of one of your customers, for its manager to claim: created
* once whatever the retries (its key names the customer); a retry answers
* the same firm, without its link.
*/
function lexopti_create_firm(array $config, string $token, string $customerId, array $firm): array
{
$firm['external_ref'] = "crm:customer:{$customerId}";
return lexopti_firms_request($config, $token, 'POST', '/v1/firms', "crm-customer-{$customerId}", $firm);
}
/** Where a firm stands: pending, claimed (its organization_id), expired or voided. */
function lexopti_firm(array $config, string $token, string $firmId): array
{
return lexopti_firms_request($config, $token, 'GET', '/v1/firms/' . rawurlencode($firmId));
}
/** A new claim link, e-mailed to the manager again: the previous one stops working. */
function lexopti_renew_claim_link(array $config, string $token, string $firmId): array
{
return lexopti_firms_request($config, $token, 'POST', '/v1/firms/' . rawurlencode($firmId) . '/claim-link');
}
if (PHP_SAPI === 'cli' && realpath($argv[0] ?? '') === __FILE__) {
$config = lexopti_config();
$token = lexopti_application_token($config);
if (($argv[1] ?? '') === 'renew') {
$renewed = lexopti_renew_claim_link($config, $token, (string) ($argv[2] ?? ''));
echo 'renewed ', $renewed['status'], ' ', $renewed['claim_url_expires_at'], PHP_EOL;
exit(0);
}
$organization = [
'name' => 'Agence du Port',
'siren' => '732829320',
'profession' => 'real_estate',
'manager' => ['email' => 'gerante@agence-du-port.example', 'first_name' => 'Claire'],
];
$firm = lexopti_create_firm($config, $token, '12', $organization);
// Show claim_url to the manager signed in to your software, never elsewhere.
echo 'created ', $firm['id'], ' ', $firm['status'], ' ', parse_url($firm['claim_url'], PHP_URL_PATH), PHP_EOL;
$retried = lexopti_create_firm($config, $token, '12', $organization);
echo 'retried ', $retried['id'], ' ', var_export($retried['claim_url'], true), PHP_EOL;
$read = lexopti_firm($config, $token, $firm['id']);
echo 'read ', $read['status'], ' ', $read['expires_at'], PHP_EOL;
}

The signature is checked on the raw body, before any JSON parsing; a wrong signature, or a timestamp more than five minutes away, answers 400. Queue the work and answer a 2xx at once; retries and replays keep the event id, which is marked as handled only once the work is queued, so a delivery that fails before is queued on its retry (receive webhooks).

webhook.php
<?php
declare(strict_types=1);
/*
* Receives LexOpti webhooks in PHP (PHP 8.1+, no extension): every delivery
* is verified as Standard Webhooks signs it, as the TypeScript SDK's
* webhooks.verify does, then deduplicated on its id. Serve it as the
* endpoint's script (PHP-FPM, or `php -S 0.0.0.0:8080 webhook.php` to try
* it), the endpoint secret (whsec_…) in LEXOPTI_WEBHOOK_SECRET.
*/
/**
* The verified event of a delivery, its id (the webhook-id header) added.
* Throws when a header is missing, the timestamp is more than five minutes
* away, or no `v1` signature is the HMAC-SHA256 of `{id}.{timestamp}.{body}`
* with the secret. Verify the raw body, before any JSON parsing.
*/
function lexopti_verify_webhook(string $payload, array $headers, string $secret, int $toleranceSeconds = 300): array
{
$headers = array_change_key_case($headers, CASE_LOWER);
$id = $headers['webhook-id'] ?? '';
$timestamp = $headers['webhook-timestamp'] ?? '';
$signatures = $headers['webhook-signature'] ?? '';
if ($id === '' || !ctype_digit($timestamp) || $signatures === '') {
throw new UnexpectedValueException('Missing webhook headers.');
}
if (abs(time() - (int) $timestamp) > $toleranceSeconds) {
throw new UnexpectedValueException('The webhook timestamp is too old or too new.');
}
$key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
if ($key === false || $key === '') {
throw new InvalidArgumentException('The webhook secret is not a whsec_ secret.');
}
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$payload}", $key, true));
// During a secret rotation a delivery carries one signature per secret.
foreach (explode(' ', $signatures) as $signature) {
[$version, $value] = array_pad(explode(',', $signature, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $value)) {
return json_decode($payload, true, 512, JSON_THROW_ON_ERROR) + ['id' => $id];
}
}
throw new UnexpectedValueException('No valid webhook signature.');
}
/**
* Where an event's id is marked as handled. A file per id stands for a
* unique key in your database.
*/
function lexopti_seen_marker(string $eventId): string
{
return sys_get_temp_dir() . '/lexopti-webhook-' . hash('sha256', $eventId);
}
/** Whether the event was already queued: retries and replays keep its id. */
function lexopti_already_seen(string $eventId): bool
{
return file_exists(lexopti_seen_marker($eventId));
}
/**
* Marks the event as handled, once it is queued: a delivery that fails
* before (a crash, a full queue) is retried by LexOpti and queued then. Two
* deliveries of the same event at the same moment may both be queued: let
* the queue's consumer deduplicate on the id too (a unique key).
*/
function lexopti_mark_seen(string $eventId): void
{
$created = @fopen(lexopti_seen_marker($eventId), 'x');
if ($created !== false) {
fclose($created);
}
}
if (PHP_SAPI !== 'cli') {
try {
$event = lexopti_verify_webhook(
(string) file_get_contents('php://input'),
getallheaders(),
(string) getenv('LEXOPTI_WEBHOOK_SECRET')
);
} catch (UnexpectedValueException $invalid) {
http_response_code(400);
exit;
}
// webhook.test is what the endpoint's test sends: accept it, nothing to do.
if ($event['type'] !== 'webhook.test' && !lexopti_already_seen($event['id'])) {
// Queue the work and answer at once: deliveries carry ids only, read
// the details through the API. The log stands for the queue.
error_log(sprintf('lexopti event %s %s %s', $event['id'], $event['type'], $event['data']['client_id'] ?? '-'));
lexopti_mark_seen($event['id']);
}
http_response_code(204);
}