tearoom1 / kirby-double-opt-in
Newsletter signup with double opt-in for Kirby: visitors choose their lists, the plugin confirms by email and hands the signup to a provider (Infomaniak first).
Package info
github.com/tearoom1/kirby-double-opt-in
Type:kirby-plugin
pkg:composer/tearoom1/kirby-double-opt-in
Requires
- php: ^8.2
- getkirby/composer-installer: ^1.2
Requires (Dev)
- getkirby/cms: ^5.0 || ^6.0
- mzur/kirby-uniform: ^5.6
- phpunit/phpunit: ^11.4 || ^12.0 || ^13.0
- s1syphos/php-simple-captcha: ^2.3
Suggests
- akibeo/kirby-altcha: Captcha 'altcha': proof of work in the browser, nothing to type
- mzur/kirby-uniform: Use the signup as a Uniform action in an existing Uniform form
- s1syphos/php-simple-captcha: Captcha 'image': characters to type from a picture
Provides
None
Conflicts
- getkirby/cms: <5.0
Replaces
None
README
Newsletter signup with double opt-in for Kirby. Visitors choose one or more newsletters in a single form, confirm by email, and only then does the plugin hand the signup to your newsletter service. Built-in adapters: Infomaniak, Brevo, Mailchimp, MailerLite, CleverReach, rapidmail, and a generic HTTP adapter for any other service or webhook. Your own provider is a small class or a closure.
Why: the embeddable forms of many newsletter services fix the groups per form, so visitors cannot pick which lists they want. And APIs such as Infomaniak's add subscribers as active at once, without a confirmation step. This plugin does the confirmation itself and calls the API only for confirmed addresses.
How it works
- The form posts email, chosen lists and extra fields to
/double-opt-in/subscribe. - The plugin checks the honeypot and the minimum fill-in time (and the captcha, if you turn one on), validates the input and stores the signup as a pending entry with a single-use token, outside the content folder.
- It sends a confirmation mail through Kirby's mailer, in the visitor's language.
- The link in the mail leads back to the page with the form (
?doi_confirm=<token>#newsletter). There the snippet confirms in the background as soon as the page loads and shows the result in the site's layout; the visitor clicks nothing. Mail scanners fetch links but run no JavaScript, so they never confirm. Without JavaScript the page shows one confirm button instead. - On confirmation, the plugin maps lists to provider groups and fields to provider field keys, calls the provider and deletes the pending entry. A second click on the link says "already confirmed".
With optIn: 'provider', the plugin hands the signup to the provider right after step 2 and the provider sends its own confirmation (see Opt-in mode).
Pending entries expire after 7 days (configurable) and are cleaned up on every signup, or with a CLI command.
Requirements
- Kirby 5 or 6
- PHP 8.2 or newer (Kirby 6 itself needs PHP 8.3 or newer)
- A working mail setup in Kirby (
email.transport)
Installation
Composer
composer require tearoom1/kirby-double-opt-in
Git submodule
git submodule add https://github.com/tearoom1/kirby-double-opt-in.git site/plugins/double-opt-in
Download
Download this repository and copy it to site/plugins/double-opt-in.
Quick start
Nothing is preset: choose a provider, the lists and the fields. site/config/config.php:
return [ 'tearoom1.double-opt-in' => [ 'provider' => 'brevo', // required, see Providers 'brevo' => ['apiKey' => getenv('BREVO_API_KEY')], 'optIn' => 'plugin', // 'plugin' (default) or 'provider' 'from' => 'newsletter@example.com', 'lists' => [ 'news' => ['label' => ['en' => 'News', 'de' => 'Neuigkeiten'], 'group' => 3, 'checked' => true], 'events' => ['label' => ['en' => 'Events', 'de' => 'Termine'], 'group' => 7], ], 'fields' => [ 'firstname' => ['key' => 'FNAME', 'autocomplete' => 'given-name'], ], ], ];
In a template:
<?php snippet('double-opt-in/form') ?>
Keep keys and tokens out of the repository: set them as environment variables on the server, or in a config file that is not committed (for example site/config/config.<host>.php).
While you build the form, use the dry-run provider. It writes signups to site/logs/double-opt-in.log instead of calling a service:
'provider' => 'log',
When something is missing or contradictory (no provider, a missing key, a mode the provider cannot do, a provider that needs lists without lists), signups fail instead of pretending to work, the PHP error log says why, and in debug mode the form shows the problems above itself.
Opt-in mode
optIn |
Who sends the confirmation | What the provider receives |
|---|---|---|
'plugin' (default) |
The plugin, with its own mail and confirmation link | The confirmed subscriber, with the confirmation time where the API has a field for it |
'provider' |
The provider, with its own double opt-in | The unconfirmed subscriber at once; the plugin is only the form |
'provider' is only offered where one confirmation covers all chosen lists (see the table below). Elsewhere the plugin refuses it with a setup error, because visitors would get one mail per list.
The form
<?php snippet('double-opt-in/form', [ 'id' => 'newsletter', // ID of the wrapper and anchor for the way back, default 'newsletter' 'lists' => ['news', 'events'], // offered lists, default all 'fields' => ['firstname'], // shown extra fields, default all 'class' => 'newsletter-signup',// extra class on the wrapper 'submit' => 'Sign up', // button text, default from the translations ]) ?>
- With one list, the form shows no checkboxes and subscribes to that list.
- With several lists, at least one must be chosen.
- With JavaScript, the bundled script sends the form in the background: no page load, the button is disabled while sending, the message appears in the status line (a live region), and field errors appear below their fields. Focus moves to the first invalid field, or to the message.
- After a successful signup only the message stays; the form is removed.
- Without JavaScript, the form posts normally and the visitor lands back on the same page with
?doi=sent(orinvalid,failed). The snippet then shows the message, hides the form aftersent, and shows the field errors afterinvalid. - The same snippet is where the confirmation link lands. It shows "Confirming your subscription …", then "Thank you, your subscription is confirmed." (or already confirmed, link no longer valid, try again later). Opening the page never confirms on the server; only the script's background request or the button does. For an expired link the form is shown again.
The script and the stylesheet are served from the plugin's assets (/media/plugins/tearoom1/double-opt-in/…) and printed once per page. Turn the script off with 'script' => false if you bundle your own; the JSON answers below have everything it needs. Without the script, links still work through the confirm button.
Copy snippets/form.php to site/snippets/double-opt-in/form.php to change the markup. Keep the data-doi wrapper with its status line, the doi-confirm form, the hidden fields doi_lang, doi_return, doi_anchor, doi_time and the honeypot.
Styles
The default stylesheet (assets/double-opt-in.css) lays the form out as one column: labels above fields, the list choice as a fieldset with its legend and one checkbox per line, and an outlined button. Colours follow the site's text colour, so light and dark themes work without changes. Text fields use zero-specificity selectors, so your own field styles win.
Adjust it with custom properties on .doi:
| Property | Default | Use |
|---|---|---|
--doi-space |
1.25rem |
Space between fields |
--doi-space-small |
0.5rem |
Label to field, between checkboxes |
--doi-radius |
0.375rem |
Corners of fields and button |
--doi-border |
text colour at 35 % | Field borders |
--doi-accent |
currentColor |
Checkboxes and focus ring |
--doi-error |
red mixed with the text colour | Error messages |
--doi-label-weight |
500 |
Labels, legend, button |
--doi-small |
0.875em |
Error messages |
--doi-button-bg |
transparent |
Button background; set it for a filled button |
--doi-button-text |
currentColor |
Button text |
--doi-button-border |
currentColor |
Button border |
.doi { --doi-accent: #2f5d50; --doi-button-bg: #2f5d50; --doi-button-text: #fff; --doi-button-border: #2f5d50; }
Or turn it off with 'styles' => false and style the classes yourself: doi (wrapper), doi-status and doi-status--{state} (empty until there is a message), doi-form, doi-field, doi-error, doi-lists, doi-list (with doi-list-label and doi-list-description inside its label), doi-submit and doi-confirm. Invalid controls carry aria-invalid="true"; the honeypot sits in a hidden wrapper.
Your own JavaScript
Post the same fields with Accept: application/json and you get JSON instead of a redirect:
{"ok": false, "state": "invalid", "errors": {"email": "Please enter a valid email address."}, "message": "Please check the marked fields."}
Status codes: 200 for sent, 422 for invalid, 500 for failed.
To confirm a link yourself, POST to /double-opt-in/confirm/<token> with Accept: application/json. The answer has the same shape; states are confirmed, already (200), expired (410) and failed (503).
Options
All options live under tearoom1.double-opt-in.
| Option | Default | Description |
|---|---|---|
provider |
null |
Required: infomaniak, brevo, mailchimp, mailerlite, cleverreach, rapidmail, http, log, a name from providers, a Provider instance or a closure returning one |
optIn |
'plugin' |
'plugin': the plugin sends the confirmation; 'provider': the provider's own double opt-in, where it covers all lists |
providers |
[] |
Your own providers: name => fn (array $options, Kirby $kirby): Provider |
infomaniak, brevo, mailchimp, mailerlite, cleverreach, rapidmail, http, log |
[] |
Settings of that provider, see Providers |
lists |
[] |
key => ['label' => string or [lang => string], 'description' => string or [lang => string], 'group' => ID or name, 'checked' => bool] |
proof |
[] |
Proof of consent after the plugin's confirmation: confirmedAt and ip as provider field keys, format; see Proof of consent |
fields |
[] |
Extra fields, none by default: name => ['label' => …, 'key' => provider field key, 'required' => bool, 'type' => 'text', 'autocomplete' => …] |
from |
no-reply@<host> |
Sender address of the confirmation mail |
fromName |
site title | Sender name |
replyTo |
from |
Reply-to address |
expiry |
7 |
Days until a pending signup and its link expire |
manageExpiry |
24 |
Hours a link to the manage page stays valid; it can be used many times until then |
resendMinutes |
10 |
A repeated signup for the same address within this time updates the pending entry without a new mail; the manage page sends at most one link per address within this time |
minSeconds |
3 |
Minimum time between rendering and sending the form; 0 disables it |
honeypot |
'website' |
Name of the honeypot field |
captcha |
false |
'image' or 'altcha', see Captcha |
captchaImage |
[] |
Image captcha: width (160), height (48), length (5), charset |
secret |
null |
Secret for signing the time field; by default a random one is created in the storage folder |
storage |
see below | Folder for pending signups |
route |
'double-opt-in' |
Path prefix of the plugin routes |
script |
true |
Print the bundled script that sends the form in the background |
styles |
true |
Print the bundled default stylesheet |
confirmStep |
'button' |
Only for the fallback page (see below): 'button' shows a confirm button, 'direct' confirms when the link opens |
page |
null |
Page ID that receives the final states of the no-JavaScript button (?doi=confirmed, …) instead of the form's own page |
language |
'en' |
Language of single-language sites (de, en, it are included) |
texts |
[] |
Text overrides, see Texts |
Options that take values (lists, fields, texts, …) also accept a closure that receives the Kirby instance, so lists can come from site content:
'lists' => function ($kirby) { $lists = []; foreach ($kirby->site()->newsletters()->toStructure() as $item) { $lists[$item->key()->value()] = ['label' => $item->label()->value(), 'group' => $item->group()->value()]; } return $lists; },
Keep list keys stable: pending signups store the keys, not the groups.
Lists
Visitors only ever send list keys. The plugin turns them into provider groups, so nobody can add themselves to a group you did not offer. A plain string is short for label and group name: 'events' => 'Events'.
'lists' => [ 'news' => [ 'label' => ['en' => 'News', 'de' => 'Neuigkeiten'], 'description' => ['en' => 'Once a month', 'de' => 'Einmal im Monat'], // optional 'group' => 3, 'checked' => true, // ticked at first ], ],
label and the optional description take a string or one per language. The form shows the description below the label, inside the same <label>, so the whole text is clickable and read as one label. The confirmation mail and the confirm step show only the label.
-
Several lists: the form shows a checkbox per list; at least one must be chosen.
-
One list: the form shows no choice, the signup goes to that list, and the mail and the confirmation name it:
'lists' => ['news' => ['label' => 'Monthly letter', 'group' => 3]],
-
No list: the subscriber goes to the provider's default (Infomaniak, Brevo, Mailchimp, MailerLite and the HTTP adapter accept that). CleverReach and rapidmail need a list; without one the setup reports an error.
Fields
Email is the only fixed field. Every other field is yours to define, and none is shown unless you add it:
'fields' => [ 'firstname' => ['key' => 'FNAME', 'required' => true, 'autocomplete' => 'given-name'], 'place' => ['key' => 'CITY', 'label' => ['en' => 'Place', 'de' => 'Wohnort', 'it' => 'Località']], 'phone' => ['key' => 'SMS', 'type' => 'tel', 'label' => 'Phone'], ],
key: the field name at the provider (Brevo attribute, Mailchimp merge tag, MailerLite field, CleverReach global attribute, rapidmail field such asfirstnameorextra1).required: defaultfalse. Optional fields carry "(optional)" after the label.type: the input type, defaulttext.label: a string or one per language; without it the plugin usestearoom1.double-opt-in.field.<name>(included:name,firstname,lastname,place).
Values are trimmed and cut to 200 characters. A plain string is short for the provider key: 'firstname' => 'FNAME'.
Captcha
Honeypot and fill-in time stop simple bots. If a bot keeps entering other people's addresses, those people get confirmation mails they never asked for, and your sender address can end up on spam lists. A captcha stops that. It is off by default; choose one per site:
'tearoom1.double-opt-in' => [ 'captcha' => 'altcha', // or 'image' ],
'altcha': the visitor's browser solves a small proof-of-work task in the background (ALTCHA), nobody types anything, no third-party service, no cookie. Needs JavaScript. Install the pluginakibeo/kirby-altcha(composer require akibeo/kirby-altcha) and give it a secret of at least 32 characters ('akibeo.altcha' => ['secret' => '…'], best in a host config that is not committed); its options (difficulty, widget look) apply here too. The widget speaks the form's language.'image': a picture with characters to type, with a "New picture" button when JavaScript runs. Works without JavaScript, but blind visitors cannot solve it. Needscomposer require s1syphos/php-simple-captchaand PHP's GD extension. The picture comes from/double-opt-in/captcha; the answer is kept in Kirby's session and counts once.
Both load outside the page, so a statically cached form page keeps working. The captcha is checked after the other fields, so a typo elsewhere does not use it up. If the chosen package or the ALTCHA secret is missing, the form shows this in debug mode and refuses signups instead of running unprotected. The manage page keeps only the honeypot, because its link request is sent as soon as the page opens. Uniform forms check the captcha themselves before the action (for ALTCHA: altcha()->verify() in the controller).
Providers
One provider per site. Each reads its settings from the option with its name.
| Provider | provider |
Settings | Lists are | optIn: 'provider' |
Checked against |
|---|---|---|---|---|---|
| Infomaniak | infomaniak |
token, domain |
groups (IDs or names) | no: the API has no double opt-in | a real account (November 2026, see below), mocked HTTP tests |
| Brevo | brevo |
apiKey; for provider mode templateId, redirectionUrl |
list IDs | yes: one mail for all lists | documented API, mocked HTTP tests |
| Mailchimp | mailchimp |
apiKey, audience, server (or a key ending in -us21), groups |
interests (default) or tags in one audience | yes: one mail for the audience | documented API, mocked HTTP tests |
| MailerLite | mailerlite |
token |
group IDs | yes, through the account switch (below) | documented API, mocked HTTP tests |
| CleverReach | cleverreach |
token, source |
group IDs, required | no: its double opt-in is per group | documented API, mocked HTTP tests |
| rapidmail | rapidmail |
username, password (API user) |
recipient list IDs, required | no: its double opt-in is per list | documented API, mocked HTTP tests |
| HTTP | http |
url, method, headers, body, format, perGroup, doi |
whatever the service expects | only with doi: true |
mocked HTTP tests |
| Dry run | log |
file |
anything | yes | tests |
Only the Infomaniak adapter has been tried against a real account so far. The others follow the providers' API documentation as of November 2026, and every adapter has tests with a fake HTTP transport. Please report what you find with a real account.
Adding lists never removes others: each adapter uses calls that add (Brevo listIds, Mailchimp interests and the tags endpoint, MailerLite groups, one CleverReach receiver or rapidmail recipient per list), and the Infomaniak adapter works around an API that replaces groups (below). Apart from Infomaniak, this follows the documentation and is not yet confirmed with real accounts.
All settings also accept endpoint and timeout (seconds, default 10).
Proof of consent
After the plugin's own confirmation, it can store when and from which address the person confirmed, at the provider:
'proof' => [ 'confirmedAt' => 'optin-date', // provider field for the confirmation time 'ip' => 'optin-ip', // provider field for the IP address of the confirming request 'format' => 'Y-m-d H:i:s', // date format of the time, default as shown, in the site's time zone ],
Nothing is sent unless you set it. The keys are provider field keys, like the key of a field, and the fields must exist at the provider (a text field is the safe choice for the time). With 'ip' => true the address goes only into the provider's own consent field, where there is one.
| Provider | Time | IP |
|---|---|---|
| Infomaniak | via proof.confirmedAt |
via proof.ip |
| Brevo | via proof.confirmedAt (attribute) |
via proof.ip (attribute) |
| Mailchimp | always in timestamp_opt |
in ip_opt |
| MailerLite | always in opted_in_at |
in optin_ip |
| CleverReach | always in activated; also via proof.confirmedAt (global attribute) |
via proof.ip (global attribute) |
| rapidmail | via proof.confirmedAt (e.g. an extra field) |
in created_ip, unless proof.ip names another field |
| HTTP | {confirmedAt}, or via proof.confirmedAt in {fields} |
{ip}, or via proof.ip in {fields} |
The IP address is personal data. If you store it, say so in your privacy statement, with the purpose (proof of consent) and how long you keep it. The plugin reads it from the confirming request ($kirby->visitor()->ip()); behind a proxy that does not pass the visitor's address on, it is the proxy's address. With optIn: 'provider' the provider records consent itself, and proof is not used. Errors from a provider go to the PHP error log with the service's own message. When a confirmed signup fails, the visitor sees "not confirmed yet" and the pending entry stays, so the same link works again once the service answers.
Infomaniak
Subscribers are active at once, so only optIn: 'plugin' makes sense.
Tests with a real account (6 November 2026) showed that POST /subscribers replaces the subscriber's groups and fields with what it gets, and PUT /subscribers/{id} replaces the groups, although the docs call both calls non-destructive. For fields, the PUT docs say so themselves: keys not sent are deleted. PUT /subscribers/assign answered with a server error. So the adapter:
- creates or updates the subscriber with the email only (
POST /subscribers), - reads the current groups, fields and status (
GET /subscribers/{id}?with=groups,fields), - writes one
PUT /subscribers/{id}with the union of old and new groups and the complete field set: stored values stay, a value from the new signup wins, an empty one never overwrites, proof fields always carry the latest confirmation, - and sets the status back to
activewhen the person had unsubscribed and has now confirmed again through the plugin. Bounced or junk addresses are left alone and logged.
A signup that changes nothing makes no third request.
- API token from the Infomaniak Manager (Profile → Developer → API tokens) with access to the Newsletter product.
- Domain ID: the numeric ID of your newsletter domain, part of the Manager URL in the newsletter tool.
- Group IDs for
lists:GET https://api.infomaniak.com/1/newsletters/{domain}/groups. Names work too, but Infomaniak creates a group for an unknown name, so IDs are safer. - Field keys:
GET https://api.infomaniak.com/1/newsletters/{domain}/fields.
If token and domain are left out, the adapter reads INFOMANIAK_NEWSLETTER_TOKEN and INFOMANIAK_NEWSLETTER_DOMAIN from the environment.
Brevo
'provider' => 'brevo', 'brevo' => ['apiKey' => getenv('BREVO_API_KEY')],
Confirmed signups use POST /v3/contacts with listIds and updateEnabled, so existing contacts are updated. Fields go to attributes; the keys (FNAME, …) must exist in your Brevo account.
For Brevo's own double opt-in, add a DOI template and the page Brevo shows after confirming:
'optIn' => 'provider', 'brevo' => ['apiKey' => getenv('BREVO_API_KEY'), 'templateId' => 12, 'redirectionUrl' => 'https://example.com/newsletter/thanks'],
This uses POST /v3/contacts/doubleOptinConfirmation and needs at least one list.
Mailchimp
'provider' => 'mailchimp', 'mailchimp' => ['apiKey' => getenv('MAILCHIMP_API_KEY'), 'audience' => 'a1b2c3d4e5'],
One audience per site. Lists are interests (groups) in that audience: group is the interest ID; interests not chosen stay as they are. With 'groups' => 'tags' they are tags instead, group is the tag name, and the adapter adds them through the member tags endpoint, which leaves other tags alone. Fields are merge tags (FNAME, …). The data centre comes from server or from the end of the API key (…-us21).
The adapter uses PUT /lists/{audience}/members/{hash}:
optIn: 'plugin': statussubscribedwith the confirmation time. Mailchimp refuses that for people who unsubscribed themselves; the adapter then setspending, so Mailchimp asks them to confirm once more.optIn: 'provider':status_if_new: pending, one confirmation mail for the audience and all chosen interests. Members who unsubscribed before are set topendingwith a second request; existing subscribers stay as they are.
MailerLite
'provider' => 'mailerlite', 'mailerlite' => ['token' => getenv('MAILERLITE_TOKEN')],
POST /subscribers on the new API (connect.mailerlite.com) creates or updates and adds the groups. Fields go to fields (name, last_name or your own).
optIn: 'plugin': statusactivewithopted_in_at. Turn the account setting "Double opt-in for API and integrations" off, or MailerLite may send its own mail as well.optIn: 'provider': statusunconfirmed. MailerLite sends its confirmation only when that account setting is on; the plugin cannot check it, so turn it on yourself. One mail covers all groups.
CleverReach
'provider' => 'cleverreach', 'cleverreach' => ['token' => getenv('CLEVERREACH_TOKEN')],
The token is the REST API token from your account (My Account → Interfaces → REST API). A receiver belongs to one group per call, so the adapter calls POST /v3/groups/{id}/receivers/upsert once per chosen list, activated at the confirmation time. Fields go to global_attributes. source (default Website) is stored with the receiver. CleverReach's own double opt-in is tied to one group, so only optIn: 'plugin' is offered.
rapidmail
'provider' => 'rapidmail', 'rapidmail' => ['username' => getenv('RAPIDMAIL_USER'), 'password' => getenv('RAPIDMAIL_PASSWORD')],
Use an API user from rapidmail's settings. A recipient belongs to one recipient list, so the adapter creates one recipient per chosen list (POST /recipients, status active, no activation mail). rapidmail has no update-or-create: when the address already exists in a list (409), the adapter looks it up and updates it. Field keys are rapidmail's: firstname, lastname, zip, extra1 … extra10. rapidmail's own double opt-in is per list, so only optIn: 'plugin' is offered.
HTTP: any other service or a webhook
For services without an adapter and for Make, Zapier or n8n:
'provider' => 'http', 'http' => [ 'url' => 'https://hook.eu1.make.com/abc123', 'method' => 'POST', // default POST 'headers' => ['Authorization' => 'Bearer ' . getenv('HOOK_TOKEN')], 'body' => [ // default: all values below 'email' => '{email}', 'lists' => '{groups}', 'name' => '{fields.firstname}', 'confirmed' => '{confirmed}', 'note' => 'Signup in {language}', ], 'format' => 'json', // or 'form' 'perGroup' => false, // true: one request per group, with {group} 'doi' => false, // true: the service sends its own confirmation ],
Placeholders: {email}, {language}, {confirmed}, {confirmedAt}, {ip} (only with proof.ip), {groups}, {lists} (list keys), {fields}, {fields.<key>} and, with perGroup, {group}. A value that is exactly one placeholder keeps its type (a list stays a list, {confirmed} stays a boolean); inside longer text it is inserted as text. Placeholders also work in the URL and in headers. Any 2xx answer counts as success.
optIn: 'provider' is accepted only with 'doi' => true, which says that the service sends one confirmation covering all lists; the request then carries confirmed: false.
Dry run
'provider' => 'log' appends each subscriber as a JSON line to the log file, with confirmed telling which mode wrote it. Nothing leaves your server.
Your own provider
Implement TearoomOne\DoubleOptIn\Providers\Provider:
use TearoomOne\DoubleOptIn\Providers\Provider; use TearoomOne\DoubleOptIn\Providers\ProviderException; use TearoomOne\DoubleOptIn\Subscriber; class SendyProvider implements Provider { public function __construct(protected string $apiKey) {} public function subscribe(Subscriber $subscriber): void { // $subscriber->email, ->groups, ->fields, ->language, ->lists, ->confirmedAt // throw new ProviderException('…', temporary: true) when the service fails } }
Implement ProviderOptIn as well (optInProblem(), requestOptIn()) if the service has a double opt-in that covers all lists, and the marker interface NeedsLists if it cannot add a subscriber without a list.
Register it:
'provider' => 'sendy', 'sendy' => ['apiKey' => getenv('SENDY_KEY')], 'providers' => [ 'sendy' => fn (array $options) => new SendyProvider($options['apiKey']), ],
For a quick integration, a closure is enough:
'provider' => fn () => new \TearoomOne\DoubleOptIn\Providers\CallbackProvider(function ($subscriber) { // … }),
Manage subscription
A page where subscribers choose or drop single lists, through a link sent by mail. Useful because many providers' own unsubscribe link ends every newsletter at once (Infomaniak sets the status to unsubscribed).
<?php snippet('double-opt-in/manage', [ 'id' => 'manage', // ID of the wrapper and anchor for the way back, default 'manage' 'lists' => ['news', 'events'], // offered lists, default all 'class' => 'my-manage', // extra class on the wrapper 'page' => $page, // page the links lead back to, default the current one ]) ?>
Link to the page from every newsletter with the subscriber's address, using your provider's merge tag (Infomaniak: *|EMAIL|*):
https://example.com/newsletter-verwalten?email=*|EMAIL|*
How it works:
- With
?email=the page says it sends a link to that address and asks for it right after loading, through the script (a POST). Mail scanners fetch every link in a campaign but run no JavaScript, so they never trigger a mail. Without JavaScript one button "Send me the link" does the same. - Without
?email=the page shows an email field. - The answer and the mail are the same whether the address is subscribed or not, so the page never tells who is on a list. At most one mail per address goes out within
resendMinutes. - The mail (templates
emails/double-opt-in/manageandmanage.html) links back to the page with?doi_manage=<token>. The token is random, stored hashed like pending signups (in<storage>/manage), and works as often as needed formanageExpiryhours (default 24). An expired or unknown token shows a message and the email field for a new link. - With a valid token the page reads the subscriber from the provider and shows the offered lists, ticked where the address is in the list's group and active. Unknown addresses see nothing ticked.
- Save sets the offered lists to the ticked ones and leaves every other group at the provider untouched, as well as the stored fields. If something is ticked and the address had unsubscribed, it is active again: the click in the mail is fresh consent, and
proofis written as after a confirmation. An unknown address is created. Nothing ticked is the same as "Unsubscribe from all". - Unsubscribe from all sets the status to unsubscribed at the provider; groups stay, as with the provider's own link.
With JavaScript, saving happens in the background and the form stays, with the result in the status line. The JSON answers have the same shape as the signup form's.
Providers: the page needs a provider that can read and change one subscriber (ManagesSubscribers). Built in for Infomaniak and the dry run log. Brevo and Mailchimp have APIs that would allow it and can follow; MailerLite cannot reactivate unsubscribed addresses through its API, CleverReach and rapidmail keep one record per list. With any other provider the page shows a setup problem (in debug mode) and does nothing. Your own provider can implement find(), manage() and unsubscribe().
The Infomaniak adapter finds an address with POST /subscribers/filter (search, all statuses) and an exact match, so looking up never creates anyone; it then reads and writes groups, fields and status as described above.
Markup: the same doi, doi-status, doi-form, doi-lists, doi-list classes as the signup form, plus doi-manage on the wrapper, doi-manage-request and doi-manage-form on the forms, doi-intro for the line above the email field, doi-actions around the buttons, and doi-unsubscribe for the second, quieter button.
Routes: POST /double-opt-in/manage/request (email, doi_lang, doi_return, doi_anchor) and POST /double-opt-in/manage/save (doi_manage, lists[], doi_offered[], doi_action save or unsubscribe). Hook: double-opt-in.manage:after with $email, $lists, $action.
Texts and languages
The plugin includes German, English and Italian. On multilingual sites, the form and the mail use the current language; the confirmation page and the result use the language of the signup.
Change a text in one of these ways:
-
Language variables of a multilingual site (
site/languages/de.php), with the full key. Since Kirby 5.6, Kirby itself no longer lets language variables override plugin strings, so the plugin reads them directly:'translations' => [ 'tearoom1.double-opt-in.form.submit' => 'Eintragen', ],
-
The
textsoption, per language or per key:'texts' => [ 'de' => ['form.submit' => 'Eintragen'], 'mail.intro' => ['de' => 'Schön, dass du dabei bist:', 'en' => 'Glad to have you:'], ],
All keys are in translations/en.php. Placeholders: {site} in mail.subject and mail.intro, {days} in mail.expiry, {field} in error.required.
Confirmation mail
The mail uses the templates emails/double-opt-in/confirm (text) and emails/double-opt-in/confirm.html. Override them in site/templates/emails/double-opt-in/confirm.php and confirm.html.php. They receive $link, $site, $lists (labels), $fields, $days, $language and $texts.
Confirmation page
Normally there is none: the link leads back to the form's page. Only when the signup came without a page to return to (a Uniform form without returnUrl, or your own JavaScript without doi_return), the link opens a small standalone page with a confirm button (snippets/page.php). To use your site's layout there, copy it to site/snippets/double-opt-in/page.php and keep the form with the button for the confirm state.
Uniform
If your site uses Kirby Uniform, start the opt-in as an action. Uniform's guards protect the form, so the plugin's own spam check is skipped:
use Uniform\Form; $form = new Form([ 'email' => ['rules' => ['required', 'email']], 'firstname' => [], ]); if ($kirby->request()->is('POST')) { $form->honeypotGuard()->doubleOptInAction([ 'lists' => ['news'], // offered list keys, default all 'emailField' => 'email', // default 'email' 'listsField' => 'lists', // default 'lists' (checkboxes named lists[]) 'returnUrl' => $page->url(), // the confirmation link comes back here 'anchor' => 'newsletter', // and scrolls to this element ]); }
With returnUrl, place the confirmation part on that page, where the link lands:
<?php snippet('double-opt-in/confirm', ['id' => 'newsletter']) ?>
It shows nothing unless the page was opened from a confirmation link. Without returnUrl, the link opens the plugin's fallback page.
Hooks
'hooks' => [ 'double-opt-in.request:after' => function ($signup) { // a confirmation mail was sent }, 'double-opt-in.confirm:after' => function ($subscriber, $signup) { // the provider accepted the subscriber, e.g. notify the site owner }, ],
Privacy and security
- Pending signups hold the email address, chosen lists, extra fields, language and return URL. Nothing else, no IP address.
- They live in
storage/double-opt-inif your site defines astorageroot, else insite/cache/double-opt-in. The folder gets a.htaccess(Require all denied) and a.gitignore. Kirby's cache flush does not touch it. - Files are named by the SHA-256 hash of the token; the token itself is never stored.
- Tokens are single-use and expire after
expirydays. After a confirmation, a small marker (token hash, time, return URL, language, no address) remembers it until the expiry, so a second click says "already confirmed". - Opening the link never confirms by itself: the form page confirms through a background request from its script, or through the button without JavaScript. Link scanners do neither. After confirming, the script removes the token from the address bar.
- Return URLs are limited to your own site.
- The fallback confirmation page sends
Cache-Control: no-store,X-Robots-Tag: noindexandReferrer-Policy: no-referrer. On your own form page, the token is in the address until the script removes it; browsers send only the origin to other sites by default. - Spam submissions (honeypot, timer) get the same answer as real ones. A wrong captcha answer gets an error, so a human can try again.
- The image captcha uses Kirby's session (a cookie) only when its picture loads; ALTCHA uses neither a session nor a cookie.
Delete expired entries from a cron job, if you want them gone without waiting for the next signup:
kirby double-opt-in:cleanup
Development
composer install
composer test
The tests use a fake provider and a fake HTTP transport; no request leaves the machine. Inside a Kirby site (site/plugins/double-opt-in), the tests also run with the site's own vendor folder.
License
Support
If the plugin is useful to you, you can support its development.