# All in Box (WordPress)

WordPress plugin that connects a site to All in Box:

- **Contacts sync** — sends form submissions to the All in Box Contacts API (v3).
  Supported builders: MetForm, Contact Form 7, WPForms, Gravity Forms, Elementor Pro, Fluent Forms.
- **Native form generator** — the `[allinbox_form]` shortcode renders an All in Box newsletter form
  (configurable fields, 7 languages, colors, target list) handled entirely by the plugin. You can also add
  `data-aib-capture` to a hand-built HTML `<form>` to have the plugin handle it. Submissions are relayed
  server-side, so the API token never reaches the browser. See the sections below.
- **WooCommerce events** (if WooCommerce is active) — sends purchase events to the contact (`custom_events`):
  order placed (classic & block checkout), payment accepted, add to cart (logged-in only). Each event is
  toggleable and mapped to an All in Box event-type handle; orders/payments also enrich the contact with the
  billing details (name, phone, address, postal code, country, city). Order/payment are ON by default,
  add-to-cart OFF. A new WooCommerce customer is synced as a contact (no subscription, tracking off).
- **Web Push** — one-click install of the All in Box Web Push SDK (injects the script and serves the
  service worker, no theme edit or FTP needed). Needs no API token. Works on a multisite or on a
  WordPress living in a subfolder: notifications are then scoped to that site's own pages.
- **Webchat** — one-click install of the All in Box chat bubble: paste the chatbot key and the widget
  script is added to every page. Needs no API token either.

## Install

1. Zip the `all-in-box` folder and upload it via *Plugins → Add New → Upload Plugin*
   (or copy the folder into `wp-content/plugins/`).
2. Activate it, then open *All in Box* in the admin menu.

## Configuration

**Connection page**
- **API URL** — usually `https://app.allinbox.com`.
- **API token** — a workspace `aib_skey_…` key with the `contacts.create_or_update` ability.
  Can also be defined in `wp-config.php`: `define( 'AIB_LEAD_SYNC_TOKEN', 'aib_skey_xxx' );`
  Once saved it is **never displayed again**: leaving the field empty keeps the stored token, and a
  *Forget the saved token* checkbox clears it explicitly.
- The token is **validated on save**. The Contacts, Newsletter form and WooCommerce pages stay out of the menu until the
  token is valid. An invalid token shows a clear error (rejected / URL unreachable / unexpected response).
- **Web Push and Webchat do not need this token**: their pages are always in the menu, so a site can use only
  the chat bubble or only push notifications without ever syncing a contact.

**Contacts page**
- **List ID** — the All in Box contact list that receives the contacts.
- **Restrict to forms** — optional. Comma-separated form identifiers. IDs are unique per builder, so
  use the builder-qualified form (e.g. `metform:11`) when two builders share an ID. Empty = all forms.
- **Subscription** — opt-in only: ticking consent subscribes the contact; leaving it unticked never
  unsubscribes an existing subscriber.
- **Field mapping** — auto-detected (email, phone, first/last name, postal code). A postal code is only
  sent together with a country (API requirement); set the default country (ISO-2) if forms have none.
- **Language** — sent with every contact: the `lang` of an `[allinbox_form]`, else the `lang` of the page
  (`<html lang>` for a hand-built form), else the current language of Polylang or WPML, else the site
  language. A language without a two-letter code is not sent. A payment carries none: the payment
  provider can confirm it from its own server, in a language that is not the customer's.

**Web Push page**
- **Channel token** — the `data-aib-token` of the All in Box Web Push channel. When set, the SDK script
  is injected site-wide and the service worker is served at `/AIBSDKWorker.js`. Use *Check setup* to verify.
- **Sites that are not at the root of their domain** (a subdirectory multisite, or a WordPress in a
  subfolder) work too: the worker is served on the site's own path, for example
  `/grasse/AIBSDKWorker.js`, and the script tag carries the matching `data-sw-path` / `data-sw-scope`.
  Notifications then cover that site's pages only, which is what you want on a network where each
  sub-site has its own channel. Nothing has to be written at the network root, and the main site of
  the network is left alone.

**Webchat page**
- **Chatbot key** — the `data-aib-chatbot-key` shown in All in Box under *Integrate on your website*.
  When set, the chat script is added to every page of the site.
- Your chatbot only answers the **site declared in All in Box**: copy the domain shown on the page into the
  chatbot's *Your website* field, and publish the chatbot. *Check setup* calls the chatbot from this very
  site and tells you which of the three is missing (unknown key, bot not published, domain not declared).

## Hand-built HTML forms (`data-aib-capture`)

The easiest way to add a form is the [`[allinbox_form]` shortcode](#native-form-generator--allinbox_form-shortcode)
below. But if you'd rather keep your own HTML markup, add `data-aib-capture` to its `<form>` tag and the
plugin becomes the backend: it handles the submit, sends the fields to All in Box server-side (the token
never reaches the browser), then shows a success message or redirects.

```html
<form data-aib-capture
      data-aib-success="Thanks, you're subscribed!"
      data-aib-redirect="/thank-you">
  <input type="email" name="email" required>
  <label><input type="checkbox" name="optin"> I agree to receive emails</label>
  <button type="submit">Subscribe</button>
</form>
```
- `data-aib-success` — message shown after a successful submit (optional; a default is shown otherwise).
- `data-aib-redirect` — URL to redirect to after success (optional; takes priority over the message).
  Must be a path or a URL **on this site**: anything else (another domain, a `javascript:` URI) is ignored.
- `data-aib-error` — message shown if the submit fails (optional).

Field detection (all optional to override):
- **Email** — auto-detected (an `input[type=email]`, or a field whose name/id contains `mail`). Force it
  with `data-aib-email` on the input.
- **Consent** — auto-detected (a checkbox whose name/id matches `opt-in/consent/newsletter/subscribe/gdpr`).
  Force it with `data-aib-optin`. Ticked consent subscribes the contact; **with no consent checkbox, a
  submit counts as the opt-in**. First/last name and phone are picked up from common field names or
  `data-aib-firstname` / `data-aib-lastname` / `data-aib-phone`.
- **Honeypot** — a hidden anti-bot field (a field named `email_address_check`, common in embedded forms,
  or one marked `data-aib-hp`): if filled, the submission is ignored.

### Security of the capture endpoint

The endpoint (`/wp-json/aib-lead-sync/v1/capture`) is public by necessity: it serves anonymous visitors,
behind page caches. It is guarded in four layers, in this order:

1. **Honeypot** — a filled hidden field answers 200 and does nothing, so a bot learns nothing.
2. **Same-origin `Origin`/`Referer`** — no REST nonce on purpose: a page served from a full-page cache
   carries an expired one, and WordPress rejects it (403) before the plugin runs. Forgeable from a script,
   hence the next two layers.
3. **Signed form token** — every rendered form carries an HMAC of (timestamp, target list). A POST that
   never loaded a page of the site is rejected, and the **target list cannot be swapped** for another list
   of the workspace. The window is 30 days, because the token lives in a page that may be cached.
4. **Ceilings** — 20 submissions per IP per 10 minutes (429 beyond), and 3 per email address per hour.
   Past the per-address ceiling the answer stays a success and nothing is sent: a genuine visitor
   re-submitting still sees the thank-you message, and nobody can use the form to bombard a third party
   with subscriptions. Adjust with the `aib_lead_sync_capture_limits` filter.

The API token never leaves the server. Opt-in only, as everywhere else.

Note: `data-aib-list` is only honoured on a form rendered by the plugin (it is covered by the signature).
A hand-built form always targets the list configured on the Contacts page.

## Native form generator — `[allinbox_form]` shortcode

Generate an All in Box-native newsletter form (handled by the plugin, no external service) by dropping the
`[allinbox_form]` shortcode anywhere (a Divi text/code module, a page, a widget). You can place several,
each with its own fields, styling, language and target list.

```
[allinbox_form lang="fr" fields="firstname,email" accent="#010101" radius="10"
   title="Newsletter" button="Je m'inscris" redirect="/merci"]
```

Attributes (all optional except the implicit email field):
- `lang` — one of `fr, en, es, de, it, nl, pt` (labels, consent text, button and messages are translated).
  Defaults to the site language, then English.
- `fields` — comma-separated, in any order: `firstname, lastname, email, phone, birthdate, address,
  postal_code, country, gender`. `email` is always included. (`postal_code` is only sent with a `country`.)
- `list_id` — target All in Box list for this form (defaults to the configured list).
- `accent`, `bg`, `text` — colors (hex). `radius` — border radius (px). `width` — max width (px).
  `font_size` — base font size in px (default `16`; all text scales from it), or `inherit` to follow the theme.
- `title`, `description` — optional heading text.
- `button` — submit label. `consent` — consent text (`no` to hide the consent box; then a submit counts as
  the opt-in). The consent checkbox is **required by default**; add `consent_required="no"` to make it optional.
  `policy` — privacy-policy URL; the policy phrase in the consent text becomes a link to it.
  `success` — message after submit. `redirect` — URL to go to after success (overrides the message);
  only a path or a URL on this site is accepted, anything else is dropped.
  `error` — message on failure.

The default consent text mentions email open-tracking ("…and the associated open tracking…") **only when
the open-tracking pixel is enabled** (the *Allow email open-tracking* setting), since ticking consent then
also authorises the pixel. Set your own `consent` text to override.

Submissions are relayed server-side (token never exposed), opt-in only, with the same honeypot/CSRF
protection as the embedded-form capture.

## Notes

- Each adapter is isolated in a try/catch: a failure on our side never breaks the host form submission.
- No secrets are stored in code; the API token lives in the WordPress options (or `wp-config.php`).
- The `[allinbox_form]` shortcode renders **nothing** until the connection and a list are configured
  (an administrator sees a short explanation instead). Better an absent form than one that silently
  falls back to reloading the page.
- The generated form posts with `method="post"`: the day the script does not run, the browser reloads
  the page instead of putting the address in the query string.
