Skip to main content

Custom CAPTCHA provider

What it does​

Add a CAPTCHA service of your own as a fourth provider next to reCAPTCHA, hCaptcha and Turnstile. Once your module registers it, the provider appears in CAPTCHA Provider under Stores → Configuration → MageMe Extensions → WebForms → Spam Protection, and every form that requires a CAPTCHA uses it on the storefront.

A provider has a server side and a browser side. The server side is an entry in etc/webforms.xml, a model that checks the visitor's answer with your service, and a block that prints the widget's settings. The browser side is a field adapter: a small script that draws the widget and hands its token to the form. The three built-in providers are built this way; the examples follow Turnstile, the simplest of them.

The examples add a provider named Northstar Shield in a module named Northstar_WebFormsShield. Put your own service, vendor and module names in their place.

A complete, working sample is on GitHub: Acme_SampleCaptcha, a provider that asks a math question, in mageme/webforms-captcha-provider-example. It runs on WebForms 4.0.1 and later, on Luma, Hyvä and Breeze, and its README lists what each file does. It's under the MIT license. It shows how to connect a provider; it isn't a hardened CAPTCHA.

Before you start​

  • A Magento module of your own with MageMe_WebForms in the <sequence> of its etc/module.xml. See Getting started for developers.
  • Your service's widget script, its site key and secret key, and the address where your server checks a token.
  • File access to the store and a shell where you can run bin/magento.

Steps​

Register the provider​

  1. Add the provider to etc/webforms.xml of your module, under captcha_types:

    <?xml version="1.0"?>
    <webforms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:MageMe_WebForms:etc/webforms.xsd">
    <captcha_types>
    <type id="northstar_shield" order="30">
    <label>Northstar Shield</label>
    <model>Northstar\WebFormsShield\Model\Captcha\NorthstarShield</model>
    </type>
    </captcha_types>
    </webforms>

    The id is the value stored in webforms/captcha/type when the provider is chosen. label is what the CAPTCHA Provider drop-down shows. The built-in types also carry a config element with option lists; only the built-in setting sources read it, so a new provider leaves it out.

Write the model​

  1. Create the model. It extends MageMe\WebForms\Model\Captcha\AbstractCaptcha, which implements MageMe\WebForms\Api\Utility\Captcha\CaptchaInterface up to the four methods your service decides:

    <?php
    declare(strict_types=1);

    namespace Northstar\WebFormsShield\Model\Captcha;

    use MageMe\WebForms\Api\Utility\Captcha\CaptchaBlockInterface;
    use MageMe\WebForms\Api\Utility\Captcha\CaptchaRendererInterface;
    use MageMe\WebForms\Model\Captcha\AbstractCaptcha;
    use MageMe\WebForms\Model\Captcha\Context;
    use Magento\Framework\App\Config\ScopeConfigInterface;
    use Magento\Store\Model\ScopeInterface;

    class NorthstarShield extends AbstractCaptcha
    {
    private const PATH = 'webforms/captcha/northstar_shield/';

    private ScopeConfigInterface $scopeConfig;

    public function __construct(
    ScopeConfigInterface $scopeConfig,
    CaptchaBlockInterface $captchaBlock,
    CaptchaRendererInterface $captchaRenderer,
    Context $context,
    array $data = []
    ) {
    parent::__construct($captchaBlock, $captchaRenderer, $context, $data);
    $this->scopeConfig = $scopeConfig;
    }

    public function isConfigured(): bool
    {
    $url = $this->setting('verify_url');
    return $this->getSiteKey() !== ''
    && $this->setting('secret_key') !== ''
    && filter_var($url, FILTER_VALIDATE_URL) !== false
    && parse_url($url, PHP_URL_SCHEME) === 'https';
    }

    public function verify(string $response): bool
    {
    $answer = json_decode($this->postCurlData($this->setting('verify_url'), [
    'secret' => $this->setting('secret_key'),
    'response' => $response,
    'remoteip' => $this->remoteAddress->getRemoteAddress(),
    ]), true);
    return is_array($answer) && !empty($answer['success']);
    }

    public function getResponseName(): string
    {
    return 'northstar-shield-response';
    }

    public function getSiteKey(): string
    {
    return $this->setting('site_key');
    }

    private function setting(string $key): string
    {
    return (string)$this->scopeConfig->getValue(self::PATH . $key, ScopeInterface::SCOPE_STORE, $this->getStoreId());
    }
    }
    Method What WebForms does with it
    isConfigured() Decides whether the form uses a CAPTCHA at all. While it returns false, no widget is drawn and submissions go through unchecked.
    verify(string $response) Checks the visitor's token on submit. false rejects the submission with getValidationFailureMessage().
    getResponseName() The name of the posted field that carries the token, read when the form posts no captcha_token.
    getValidationFailureMessage(), getTechnicalFailureMessage() The messages for a rejected token and for a submission that arrives without one. AbstractCaptcha has English defaults; the built-in providers read them from the store configuration.

    postCurlData() and getStoreId() come from AbstractCaptcha. getStoreId() returns the store view of the form being rendered or checked: WebForms sets it before it reads any key.

Write the block and its template​

  1. Create the block. It extends MageMe\WebForms\Block\Form\Element\Captcha\AbstractCaptcha:

    <?php
    declare(strict_types=1);

    namespace Northstar\WebFormsShield\Block\Captcha;

    use MageMe\WebForms\Block\Form\Element\Captcha\AbstractCaptcha;

    class NorthstarShield extends AbstractCaptcha
    {
    protected $_template = self::TEMPLATE_PATH . 'northstar_shield.phtml';
    }

    TEMPLATE_PATH is form/element/captcha/type/, resolved in your module.

  2. Create view/frontend/templates/form/element/captcha/type/northstar_shield.phtml. It prints no widget, only a hidden descriptor for the adapter, exactly as the built-in templates do:

    <?php
    /**
    * @var \Northstar\WebFormsShield\Block\Captcha\NorthstarShield $block
    * @var \Magento\Framework\Escaper $escaper
    */
    /** @var \Northstar\WebFormsShield\Model\Captcha\NorthstarShield $captcha */
    $captcha = $block->getCaptcha();
    $uid = $block->getUid();
    $descriptor = [
    'type' => 'northstar_shield',
    'critical' => true,
    'containerId' => 'captcha-container-' . $uid,
    'options' => [
    'siteKey' => $captcha->getSiteKey(),
    'languageCode' => $block->getLocale(),
    'responseFieldName' => $captcha->getResponseName(),
    ],
    ];
    ?>
    <div hidden data-mm-form-uid="<?= $escaper->escapeHtmlAttr($uid) ?>"
    data-mm-field="<?= $escaper->escapeHtmlAttr(json_encode($descriptor)) ?>"></div>

    type names the adapter that mounts the widget. critical: true means the form doesn't start, and so can't be submitted, if the adapter fails to load or mount. containerId is the element the form prints for the CAPTCHA, the same id on Luma, Hyvä and Breeze. The site key is public; never put the secret key in the descriptor.

Wire the classes together​

  1. In your module's global etc/di.xml, give the model the core renderer and your block:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Northstar\WebFormsShield\Model\Captcha\NorthstarShield">
    <arguments>
    <argument name="captchaRenderer" xsi:type="object">MageMe\WebForms\Block\Form\Element\Captcha\Renderer</argument>
    <argument name="captchaBlock" xsi:type="object">Northstar\WebFormsShield\Block\Captcha\NorthstarShield</argument>
    </arguments>
    </type>
    </config>

Write the adapter​

  1. Create the adapter script, view/frontend/web/js/northstar-shield.js. The form controller loads it the first time a form needs the northstar_shield adapter and calls its mount(). The script below is the WebForms side only: it can't pass a check until you add your service's own calls at the two comments, so until then every submission stops with the "security check" message.

    'use strict';

    MageMe.WebForms.adapters.northstar_shield = {
    mount: (marker, cfg) => new Promise((resolve, reject) => {
    const rootEl = document.getElementById(cfg.containerId);
    if (!rootEl) {
    reject(new Error(`captcha container #${cfg.containerId} missing`));
    return;
    }
    const cid = `northstar-shield-${cfg.containerId}`;

    const start = () => {
    const widget = document.createElement('div');
    widget.setAttribute('cid', cid);
    rootEl.replaceChildren(widget);
    rootEl.classList.add('wf-captcha-shown');

    let token = '';
    // Draw your service's widget into `widget` with cfg.options.siteKey,
    // and set `token` from the widget's success callback.

    const drawing = new AbortController();
    const live = () => {
    if (!widget.isConnected) {
    drawing.abort();
    }
    return widget.isConnected;
    };
    window.addEventListener('mm-form-captcha-promise', (e) => {
    if (e.detail?.cid !== cid || !e.detail.form || !live()) {
    return;
    }
    e.detail.form.setCaptchaPromise(() => Promise.resolve(token));
    }, {signal: drawing.signal});
    window.addEventListener('mm-form-captcha-reload', (e) => {
    if (e.detail?.cid !== cid || !live()) {
    return;
    }
    token = '';
    // Reset your service's widget here.
    }, {signal: drawing.signal});
    };

    MageMe.WebForms.captchaGate(rootEl, start);
    resolve();
    }),
    };

    Three rules keep the adapter working in every form:

    • Draw inside start, through the gate. With Require CAPTCHA for set to Guests Only, the form keeps the container hidden and calls start only for a guest, or after the server refuses a submission for a missing CAPTCHA. With any other setting start runs at once. A widget drawn outside start shows to signed-in customers too. The built-in reCAPTCHA, hCaptcha and Turnstile adapters use the same gate.
    • Always resolve the mount, also while start is held back. The form starts only after every field has mounted.
    • Keep wf-captcha-shown on the container while your widget is drawn in place. Without it the form gives the CAPTCHA no room.

    The form engine talks to a CAPTCHA through three things, all in the core form.js:

    Contract What the adapter does
    A div with a cid attribute inside the container The engine looks for div[cid] in #captcha-container-<uid> and sends the attribute's value back in both events, so each adapter answers only for its own widget. The value must be unique on the page: the built-in adapters store the widget id the service's render() returns, the example builds it from the container id.
    mm-form-captcha-promise on window The engine asks for a token source; detail holds cid and the engine as form. Answer with detail.form.setCaptchaPromise(fn). On submit the engine calls fn(cid, form) and posts what it resolves to as captcha_token. An empty token stops the submit with "The security check is not complete yet."
    mm-form-captcha-reload on window The engine asks for a fresh widget, for example after a successful submission when the form stays on the page; detail holds cid.

    A popup or a fragment can draw the form again. Stop listening once your widget is no longer on the page, as the example does with live().

  2. Register the adapter for the storefront in etc/frontend/di.xml. The key must match the descriptor's type and may use lowercase letters, digits, _ and -, starting with a letter:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MageMe\WebForms\Block\Init">
    <arguments>
    <argument name="adapters" xsi:type="array">
    <item name="northstar_shield" xsi:type="string">Northstar_WebFormsShield::js/northstar-shield.js</item>
    </argument>
    </arguments>
    </type>
    </config>

    The adapter list is printed for every storefront stack, so the same adapter runs on Luma, Hyvä and Breeze. It loads as a plain script, not as a RequireJS module.

Add the settings​

  1. Add the keys to Spam Protection in etc/adminhtml/system.xml, shown only while your provider is chosen:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
    <section id="webforms">
    <group id="captcha">
    <group id="northstar_shield" translate="label" type="text" sortOrder="70"
    showInDefault="1" showInWebsite="1" showInStore="1">
    <depends>
    <field id="type">northstar_shield</field>
    </depends>
    <label>Northstar Shield</label>
    <field id="site_key" translate="label" type="obscure" sortOrder="10"
    showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Site Key</label>
    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
    </field>
    <field id="secret_key" translate="label" type="obscure" sortOrder="20"
    showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Secret Key</label>
    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
    </field>
    <field id="verify_url" translate="label" type="text" sortOrder="30"
    showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Verification URL</label>
    </field>
    </group>
    </group>
    </section>
    </system>
    </config>

    Declare the two keys as encrypted in etc/config.xml too, as WebForms does for its own providers, so they are decrypted when read:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
    <webforms>
    <captcha>
    <northstar_shield>
    <site_key backend_model="Magento\Config\Model\Config\Backend\Encrypted"/>
    <secret_key backend_model="Magento\Config\Model\Config\Backend\Encrypted"/>
    </northstar_shield>
    </captcha>
    </webforms>
    </default>
    </config>

Install and switch it on​

  1. Enable the module and update the store:

    bin/magento module:enable Northstar_WebFormsShield
    bin/magento setup:upgrade
    bin/magento cache:clean
  2. Go to Stores → Configuration → MageMe Extensions → WebForms → Spam Protection. Select Northstar Shield in CAPTCHA Provider, enter the keys and the verification URL, and click Save Config. Which visitors get a CAPTCHA is still decided by Require CAPTCHA for and each form's own setting. See Settings: Spam Protection.

What you should see​

  • CAPTCHA Provider lists Northstar Shield after the three built-in providers, and the Northstar Shield group with your keys appears when you select it.
  • On a form that requires a CAPTCHA, your widget appears in the form's CAPTCHA container, where the built-in widgets appear. With Require CAPTCHA for set to Guests Only, a signed-in customer doesn't see it.
  • A submission with a token your service accepts is saved. A submission whose token your service rejects shows getValidationFailureMessage().
  • In the browser, a form whose adapter has no token yet doesn't post: it shows "The security check is not complete yet." A request that reaches the server with no token at all, such as one sent without the page's script, gets getTechnicalFailureMessage().

Limits​

  • An unconfigured provider stops submissions. While isConfigured() returns false, forms render without a widget, and a form that requires a CAPTCHA refuses every submission with "Captcha is not set up on this store. Please contact the store owner." var/log/system.log gets a warning that names the form. The builder's CAPTCHA panel then says to add "the Site Key and Secret Key", even when your provider has no keys.
  • An unknown provider id falls back to reCAPTCHA. If your module is disabled while the store still has your provider selected, the form uses the reCAPTCHA model with its own keys. The builder reports "This captcha provider is not installed."
  • One solved CAPTCHA covers one submission of that form. After verify() accepts a token, WebForms marks the form as verified in the visitor's session and doesn't call verify() again for that form until a submission is stored. A retry after a failed field check or the Review Before Submit step doesn't ask twice.
  • The verification request. postCurlData() sends a POST with Magento's cURL client and returns an empty string when the request fails. Return false from verify() for an answer you can't read.
  • Storefront only. This page covers forms submitted from the storefront. How REST and GraphQL submissions pass a CAPTCHA is not covered here.
  • No <script> in the template. Load your service's widget script from the adapter. A template that prints an executable script breaks forms in a popup or a fetched slide-out.

Troubleshooting​

  • The provider isn't in CAPTCHA Provider. Check captcha_types in your etc/webforms.xml and clean the cache.
  • No widget appears. Check that isConfigured() returns true for the form's store view, that Require CAPTCHA for applies to the visitor, and the browser console for "unknown field adapter" (the adapter isn't registered under the descriptor's type) or "adapter script did not register" (the script didn't set MageMe.WebForms.adapters.<type>).
  • Every submission says the security check is not complete. The adapter never answered mm-form-captcha-promise, or the cid it compares with isn't the one on its div. The engine keeps asking until a function is set.
  • Every submission is rejected. verify() returned false: check the secret key, the verification URL and your service's answer format.

What's next​

Applies to WebForms 4Last reviewed October 14, 2026