1 Remote sync API
Robin edited this page 2026-11-22 21:08:16 +01:00

Remote sync API

Keep LRob - Email Toolkit's contacts and lists up to date from another system — a CRM, a billing tool, a customer database — while every email keeps leaving from your site. Available since 0.9.6.

Version française

What it does

Your system knows who your customers are and what they bought. With this API it tells the plugin, and the plugin keeps the lists:

  • contacts are created and updated in batches;
  • lists follow your segments (all customers, customers of an offer, of a server, former customers…), and nobody edits them by hand;
  • departures are handled: a contact you stop sending leaves your lists;
  • what happens on the site comes back to you: unsubscribes, bounces, addresses in error.

Your system decides who belongs to which list; the plugin stores that state and never evaluates a rule of its own.

Two kinds of list

Service list Optional list
For what the contract requires: incidents, maintenance, price or offer changes offers, promotions, news, former customers
Who active customers only whoever you put there, minus those who said no
An unsubscribe from offers does not stop them stops them, durably
Leaving this list alone not possible while the service is active yes, from the preferences page
Email footer "You receive this message because you have an active service…" + preferences link, no unsubscribe link the usual footer, unsubscribe included

A newsletter whose audience is only service lists is a service message. It cannot be mixed with other lists, and it does not leave if your system has not synced for 24 hours — so a former customer is never mailed from an out-of-date list. Each recipient's membership is checked again right before their email leaves.

A former customers list is simply an optional list you move people into when they leave.

The promises the plugin keeps

These hold whatever your system sends:

  1. A sync never changes a marketing choice and never sends an email.
  2. Someone who unsubscribed from offers, or left one optional list, is never put back by a sync. The refusal survives the deletion of the record (only a hash of the address is kept) and an address change on your side.
  3. Service lists hold whoever you put there, and nobody else.
  4. After the end of the relationship you report: no more offers after 3 years, the contact erased after 5 years (both adjustable on the site). Someone who signed up by themselves keeps their own subscription.

Getting a key

In WordPress: Newsletters → Remote sync → Generate an API key. Name it after your system. You get three values, shown once:

Value Example
Address https://example.com/wp-json/lrob-etk/v1/sync/
Key etk_4c00c1d140c04c6a
Secret 64 hexadecimal characters — keep it like a password

The secret never travels: it signs each request. Revoke a key from the same screen; its contacts and lists stay as they are. While no key exists, the API answers 404 everywhere.

Signing a request

Every request carries four headers:

Header Value
X-Lrob-Etk-Key the key
X-Lrob-Etk-Timestamp Unix time in seconds; ±5 minutes accepted
X-Lrob-Etk-Nonce a random value, never reused (128 characters max)
X-Lrob-Etk-Signature hex(HMAC-SHA256(secret, canonical string))

The canonical string is five lines joined by \n:

METHOD in capitals
path?query exactly as sent (e.g. /wp-json/lrob-etk/v1/sync/changes?since=42)
timestamp
nonce
hex(SHA-256(raw body)), the hash of an empty string when there is no body

PHP:

function etk_request(string $site, string $key, string $secret, string $method, string $route, ?array $payload = null): array
{
    $path  = '/wp-json/lrob-etk/v1' . $route;
    $body  = $payload === null ? '' : json_encode($payload);
    $ts    = (string) time();
    $nonce = bin2hex(random_bytes(16));
    $sig   = hash_hmac('sha256', implode("\n", [strtoupper($method), $path, $ts, $nonce, hash('sha256', $body)]), $secret);
    $ch = curl_init($site . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => strtoupper($method),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => $body !== '' ? $body : null,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            "X-Lrob-Etk-Key: $key",
            "X-Lrob-Etk-Timestamp: $ts",
            "X-Lrob-Etk-Nonce: $nonce",
            "X-Lrob-Etk-Signature: $sig",
        ],
    ]);
    $out = curl_exec($ch);
    return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), json_decode((string) $out, true)];
}

[$status, $data] = etk_request('https://example.com', 'etk_…', '…', 'GET', '/sync/ping');

Shell (bash + openssl + curl):

SITE=https://example.com KEY=etk_… SECRET=…
METHOD=GET PATH_Q=/wp-json/lrob-etk/v1/sync/ping BODY=''
TS=$(date +%s); NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIG=$(printf '%s\n%s\n%s\n%s\n%s' "$METHOD" "$PATH_Q" "$TS" "$NONCE" "$BODY_HASH" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -s -X "$METHOD" "$SITE$PATH_Q" -H "X-Lrob-Etk-Key: $KEY" -H "X-Lrob-Etk-Timestamp: $TS" \
     -H "X-Lrob-Etk-Nonce: $NONCE" -H "X-Lrob-Etk-Signature: $SIG" -H 'Content-Type: application/json' \
     ${BODY:+--data "$BODY"}

A refused signature, an unknown or revoked key, a reused nonce, a clock more than 5 minutes off: 401 with a code (unauthorized, clock_skew). A body over 1 MiB: 413.

Endpoints

All routes start with /wp-json/lrob-etk/v1. Bodies and answers are JSON.

Method Route Does
GET /sync/ping API and plugin version, your source name, server time, number of open alerts, retention delays
GET /sync/lists your lists: key, name, purpose, members, reach (who a send would reach)
PUT /sync/lists/{key} create or update a list
DELETE /sync/lists/{key} delete a list (409 list_in_use while a newsletter not yet sent uses it)
POST /sync/contacts create or update up to 500 contacts
GET /sync/contacts/{id} one contact as the site sees it
DELETE /sync/contacts/{id} release a contact: out of all your lists, record kept
POST /sync/contacts/{id}/erase erase the person's data (a deletion request handled on your side)
POST /sync/runs start a full reconciliation
POST /sync/runs/{run}/commit finish it: contacts not seen are released
DELETE /sync/runs/{run} cancel it
GET /sync/changes?since={cursor} what happened on the site to your contacts

Lists

PUT /wp-json/lrob-etk/v1/sync/lists/server-alpha
{"name": "Customers on alpha", "description": "Incidents and maintenance", "purpose": "service"}
  • {key}: your stable identifier — lower case letters, digits, ., _, -, up to 100 characters.
  • purpose: service or optional. It cannot change once the list has members.
  • visibility (optional lists only): public shows the list on the preferences page, where people can leave it; private (default) does not. Service lists are always shown, greyed, to their members.
  • Answer 201 when created, 200 when updated, with the list.

Contacts

POST /wp-json/lrob-etk/v1/sync/contacts
{
  "run_id": "nightly-2026-11-05",
  "contacts": [
    {
      "external_id": "ctc_1042",
      "email": "jane@example.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "language": "fr_FR",
      "fields": {"company": "Example Ltd"},
      "lists": ["customers", "offer-hosting", "server-alpha", "offers"],
      "relationship_ended_at": null
    }
  ]
}
Field
external_id required — your contact id, up to 100 printable characters; it is how the plugin follows the person, even when the address changes
email required
first_name, last_name, name, phone, address_line, address_line2, address_postcode, address_city, address_region, address_country (ISO-2), gender (female / male / other / prefer_not_to_say), language optional; absent = unchanged, present = replaced
fields custom fields already defined on the site (Subscribers → Custom fields); an unknown key comes back as a warning
lists the complete set of your lists for this contact: lists missing from it are left. Lists created on the site by hand are never touched
relationship_ended_at ISO 8601 date the person stopped being a customer, null while they are one; starts the retention clock
run_id optional, only recorded in the journal

The answer has one result per contact, in the same order, plus totals. The request succeeds (200) even when some contacts are refused.

{
  "results": [{
    "external_id": "ctc_1042",
    "outcome": "updated",
    "recipient": {"kind": "subscriber", "id": 1517},
    "marketing_status": "refused",
    "address_health": "ok",
    "lists_applied": ["customers", "offer-hosting", "server-alpha"],
    "lists_refused": [{"list": "offers", "reason": "unsubscribed"}]
  }],
  "counts": {"updated": 1}
}
outcome Meaning
created a new contact
linked the address already existed on the site (a subscriber or a WordPress account); it is now yours too
updated / unchanged something changed / nothing did
conflict the new address already belongs to someone else; nothing written, an alert is raised
invalid see code: invalid_external_id, invalid_email, invalid_lists, unknown_list (+ list), invalid_relationship_ended_at

lists_refused[].reason: unsubscribed (no offers for this person), left (they left this list), retention (relationship ended too long ago). address_health: ok, bounced (the address does not work), blocked (excluded by hand), complained (marked an email as spam; service messages still go). marketing_status: subscribed or refused.

Sending the same batch twice gives unchanged the second time: you can retry any request safely.

One contact

GET /sync/contacts/{id} returns the address, marketing_status, address_health, service_mailable, marketing_mailable, lists, lists_left, relationship_ended_at, released. Url-encode the id.

DELETE /sync/contacts/{id} takes the contact out of all your lists and keeps the record (their own subscriptions stay). POST /sync/contacts/{id}/erase erases what the site holds about the person; if they had refused offers, only a hash of the address is kept so that refusal is never lost.

Full reconciliation

Push changes as they happen (a new customer, a cancelled offer, a migration), and once a night run a full pass so nothing drifts:

  1. POST /sync/runs with {"id": "nightly-2026-11-05"} — your own id, 8 to 64 letters, digits, - or _. Calling it again with the same id is harmless. Only one run is open at a time (409 run_in_progress); an open run expires after 24 hours.
  2. Push every current contact through POST /sync/contacts.
  3. POST /sync/runs/{id}/commit. Every contact of yours not pushed since the run started is released.

Safety brake. If the commit would release more than 20 % of your contacts, or more than 20 % of a service list's members, it is refused with 409 mass_release, an alert is raised on the site and in the change feed. If the departure is real, commit again with {"confirm_release": N}, N being the exact number given in the refusal. A second commit returns the same summary.

What happens on the site

GET /sync/changes?since=0 then ?since={cursor} with the cursor of the previous answer (more: true means read again at once):

{"changes": [{"id": 43, "external_id": "ctc_1042", "type": "bounced", "detail": "550 5.1.1 user unknown", "at": "2026-11-05T09:12:00+00:00"}], "cursor": 43, "more": false}
type
unsubscribed / subscribed the person refused / accepted offers again
bounced the address does not work (non-existent, or keeps refusing)
complained the person marked an email as spam
forgotten the record was erased on the site
email_updated the address changed following your push
alert / alert_handled an alert opened (detail = code) / marked handled on the site

Entries are kept 90 days.

Alerts

An address in error is serious: a customer who no longer receives invoices or answers must be reached another way. The plugin opens an alert when a contact of yours bounces, when a service message cannot be sent to them, when an address conflicts, when a commit hits the brake, or when a service message is held because your lists are out of date. Alerts are shown on the site (Newsletters → Remote sync, with a counter on the menu) and come to you through the change feed (alert) and /sync/ping (open_alerts).

Errors

Errors use the WordPress format: {"code": "…", "message": "…", "data": {"status": …}}.

Status Codes
400 bad_request, invalid_purpose, invalid_visibility, invalid_name, invalid_run_id
401 unauthorized, clock_skew
404 not_found (unknown contact, list or run — or no key exists yet)
409 list_in_use, purpose_locked, run_in_progress, run_closed, mass_release
413 body_too_large, too_many (more than 500 contacts)
500 internal

Good practice

  • Send changes as they happen, then a nightly reconciliation.
  • Batches of 100 to 500 contacts; retry on a network error — every call is safe to repeat.
  • Read /sync/changes regularly and show the alerts to whoever handles your customers.
  • Answers are never cached (Cache-Control: no-store); if your site sits behind a page cache, make sure it honours that header.