Add-on integration contract
Overview
An integration add-on sends new submissions to an outside service: a CRM, a helpdesk, a mailing list or a webhook. WebForms does the plumbing. The add-on registers two classes under one integration code, a definition that says when a form sends and which form settings point at fields, and a handler that makes the call to the service. WebForms then hands each new submission to the handler through a message queue, retries failed deliveries, offers a send action in the submissions grid, and keeps the add-on's field references right when a form is imported or duplicated.
All eight MageMe integration add-ons (Zapier, HubSpot, Salesforce, Zoho, Freshdesk, Zendesk, Klaviyo,
Mailchimp) are built on this contract. Paths below are relative to the MageMe_WebForms module unless a
module is named.
How a submission reaches the service
Helper\Result\PostHelper::postResult()saves a submission (Helper/Result/PostHelper.php). When the save succeeded and the submission is new, it callsModel\Integration\SubmitTrigger::fire()as its last step: afterwebforms_result_submit, the reference number and the confirmation, and before the plugins ofpostResult()run. Edits never reach this step.SubmitTriggerasks every definition inModel\Integration\DefinitionPoolwhether it is on for the form (isEnabledFor()), and callsModel\Integration\Dispatcher::dispatch($code, $result, true)for each one that is (Model/Integration/SubmitTrigger.php). An error is logged; the submission never fails.dispatch()publishes a message to the topicmageme.webforms.integration.send(Model/Integration/Dispatcher.php). For a new submission of a form that does not store submissions, made outside the admin, it calls the handler at once instead, because the submission is deleted right after.- The consumer
Model\Integration\Consumer::process()sets the submission's store view as the current store, loads the submission and calls the handler (Model/Integration/Consumer.php). A submission deleted in the meantime is skipped. - A handler that throws is retried, as described under Errors and retries.
The queue, the consumer and how to run it are on CLI, cron and queues.
What the add-on registers
| Where | What | Item |
|---|---|---|
etc/di.xml (global) | MageMe\WebForms\Model\Integration\HandlerPool, argument handlers | <item name="<code>" xsi:type="object"> your handler. The MageMe add-ons pass the handler's \Proxy. |
etc/di.xml (global) | MageMe\WebForms\Model\Integration\DefinitionPool, argument definitions | <item name="<code>" xsi:type="object"> your definition, under the same code. |
etc/db_schema.xml | Columns on mm_webforms_form | The add-on's form settings: an on/off column, field id columns, and a text column for each JSON setting. |
etc/adminhtml/di.xml | Virtual type MageMe\WebForms\Ui\Component\Form\Form\Modifier\Pool, argument modifiers | The modifier that adds the add-on's section to the form settings. |
view/adminhtml/ui_component/webforms_result_listing.xml | An action in listing_massaction | The grid's send action, with an integration item. Optional. |
etc/adminhtml/routes.xml and a controller | Admin route | The URL the grid action posts to. Optional. |
Register both pools in the global etc/di.xml: the consumer runs from the command line and the storefront
submits in the frontend area, so a registration in etc/adminhtml/di.xml would be missing there.
DefinitionPool refuses a definition registered under a code other than its own getCode(), and both pools
refuse an object that does not implement their interface (Model/Integration/DefinitionPool.php,
Model/Integration/HandlerPool.php).
Interfaces
Definition
MageMe\WebForms\Api\IntegrationDefinitionInterface (Api/IntegrationDefinitionInterface.php), @api.
| Method | Returns | Used for |
|---|---|---|
getCode() | string | The integration code; the same as the handler's. |
isEnabledFor(FormInterface $form) | bool | Whether a new submission of this form is sent, and whether the grid offers the send action. |
getFieldIdKeys() | string[] | Form data keys that each hold one field id, such as the field with the customer's email. Remapped on import and duplicate. |
getSerializedMappings() | array<string, string> | Each array setting kept as JSON on the form: data key → column. WebForms serializes these columns on save (Model/ResourceModel/Form.php, getSerializableFields()), and remaps rows that name a field under field_id on import and duplicate. |
The 3.x plugins named GetSerializableFields, which registered an add-on's serialized columns, are gone from the
MageMe add-ons: getSerializedMappings() does that job.
The class is built on every submit and every form load. Keep it light: constants, the form, and at most
ScopeConfigInterface, a logger or class_exists(). Never inject the add-on's API client, handler or a
repository.
Account check
MageMe\WebForms\Api\IntegrationAccountAwareInterface (Api/IntegrationAccountAwareInterface.php),
@api, optional, implemented by the definition.
| Method | Returns | Used for |
|---|---|---|
isAccountConfigured(?int $storeId) | bool | Whether the credentials are filled in for the store view (null for the default scope). The grid shows the send action only where this is true. Read configuration only; never call the service. |
A definition without this interface counts as configured.
Handler
MageMe\WebForms\Api\IntegrationHandlerInterface (Api/IntegrationHandlerInterface.php).
public function handle(IntegrationMessageInterface $message, ResultInterface $result): void;
The same handler serves the queue and the grid's send action. From the queue it runs in the submission's store
view; from the grid, and for the immediate send of an unstored submission, in the store of the request. Read
store-scoped settings with $message->getStoreId(). Check the form's on/off setting again inside the handler:
a queued message can outlive the switch. The interface's docblock asks for a short timeout of 10 seconds, a fresh
CurlFactory client per request, and an empty Expect header (Api/IntegrationHandlerInterface.php).
To read an answer the way a service needs it, call
$field->getValueForIntegration($result->getFieldArray()[$fieldId] ?? null, (int)$result->getId())
(Model/Field/AbstractField.php). It returns plain data: a string for one answer, a list of strings for
an answer that holds several values, no HTML and no date formatting. File fields need the submission id.
Message
MageMe\WebForms\Api\Data\IntegrationMessageInterface (Api/Data/IntegrationMessageInterface.php),
implemented by Model\Integration\Message.
| Key | Getter | Meaning |
|---|---|---|
integration_code | getIntegrationCode(): string | The handler's code. |
result_id | getResultId(): int | The submission. |
is_new | getIsNew(): bool | true from the submission flow; false from the grid's send action. |
store_id | getStoreId(): int | The submission's store view. |
payload | getPayload(): ?string | Optional JSON from the caller. Never put personal data in it: it is stored in the queue table. |
attempt | getAttempt(): int | 1 for the first delivery, then 2 and 3. |
not_before | getNotBefore(): ?int | Unix time before which a retry is not delivered; null when due. |
Dispatcher
MageMe\WebForms\Model\Integration\Dispatcher (Model/Integration/Dispatcher.php).
| Method | Behaviour |
|---|---|
dispatch(string $code, ResultInterface $result, bool $isNew, ?string $payload = null) | Queues the delivery. Never throws: an unknown code is logged as a warning, any other error as an error. A new submission object is dispatched once per code; a repeat with the same object and code is ignored, so an add-on that still dispatches on its own does not send twice. |
send(string $code, ResultInterface $result, bool $isNew = false, ?string $payload = null) | Calls the handler at once and lets its exception through. For admin actions. Throws NotFoundException when no handler has the code. |
WebForms calls dispatch() for new submissions itself. Call it from your own code only for an extra trigger of
your add-on; do not observe webforms_result_submit to send new submissions.
Attach uploaded files
The files of a File field are MageMe\WebForms\Api\Data\FileDropzoneInterface objects. The pictures of a
Gallery field come from MageMe\WebForms\Api\FileGalleryRepositoryInterface::getById(). Both give
getFullPath(), getMimeType() and getName(). The helpdesk add-ons attach them to tickets this way. From the
Freshdesk add-on (excerpt):
if ($field instanceof File) {
$field->setData('result', $result);
foreach ($field->getFilteredFieldValue() as $file) {
$value[] = ['path' => $file->getFullPath(), 'type' => $file->getMimeType(), 'name' => $file->getName()];
}
} elseif ($field instanceof Gallery) {
foreach ($field->parseValue($values[$mapField[FieldInterface::ID]]) as $imageId) {
try {
$file = $this->fileGalleryRepository->getById((int)$imageId);
} catch (NoSuchEntityException $e) {
continue;
}
$value[] = ['path' => $file->getFullPath(), 'type' => $file->getMimeType(), 'name' => $file->getName()];
}
}
To list the files of one field of one submission, call
MageMe\WebForms\Api\FileDropzoneRepositoryInterface::getListByResultAndFieldId(int $resultId, int $fieldId).
Errors and retries
A throw from the handler means "try again". The consumer delivers a message up to three times in all
(Consumer::MAX_ATTEMPTS, Model/Integration/Consumer.php); the second try waits at least 60 seconds after
the first failure and the third at least 300 seconds after the second (RETRY_DELAYS). After the third
failure the message is dropped with an error in the log. In the grid's send action, a throw counts the
submission as failed and the others are still sent.
| Situation | What the handler does | Consumer | Grid send action |
|---|---|---|---|
| Delivered, whatever else the answer says | Return | Done | Counted as sent |
| Deliberately not sent: integration off for the form, nothing to send | Return | Done | Counted as sent; return a skip reason from the controller to count it as skipped |
Timeout, connection error, HTTP status 400 or higher, an error in the answer | Throw any exception | Retried | Counted as failed |
Service down or asked to slow down (HTTP 5xx, 429) | Throw Api\Exception\IntegrationUnavailableException; pass retryAfterSeconds when the service named a wait | Retried, no sooner than the named wait, up to 3600 seconds | Failed: "did not answer or asked to wait" |
| The service refused the data itself and a later try cannot change that | Throw Api\Exception\IntegrationRejectedException | Logged, not retried | Failed: "refused the data" |
Credentials no longer accepted (HTTP 401) | Throw Api\Exception\IntegrationAuthExpiredException | Retried | Failed: "did not accept the credentials" |
| A list of the service the handler needs is not known | Throw Api\Exception\IntegrationListUnknownException | Retried no sooner than the list may be fetched again | Failed |
Judge an HTTP answer by "status 400 or higher", not by "outside 2xx": Magento's Curl client reports the first
status of the transfer, which can be a 100 Continue or a followed redirect.
IntegrationRejectedException and IntegrationUnavailableException take an optional vendorReason, the
service's machine error code and field name, such as REQUIRED_FIELD_MISSING LastName. WebForms adds it to its
log lines only when it is made of Latin letters, digits and _ . : / - in words separated by single spaces, up
to 80 characters (Api/Exception/IntegrationVendorReasonInterface.php). Never put the service's message text
there: it may quote what the visitor typed.
When the service accepts an idempotency key, inject MageMe\WebForms\Model\Integration\IdempotencyKey and send
what its get($code, $resultId) returns (Model/Integration/IdempotencyKey.php):
<installation>-<code>-<submission id>, the same on every path, so a repeated delivery is recognised. The
installation part is a hash of the first encryption key and the default base URL, so a staging copy of the
database does not reuse the live store's keys. HubSpot, Salesforce, Zoho, Zendesk and Klaviyo use it.
The grid's send action
The submissions grid of a form can offer a send action, such as Send to HubSpot, in its Actions menu. It sends the selected
submissions at once, new or not, through Dispatcher::send(), and reports how many were sent, skipped and
failed.
| Part | Base class or setting |
|---|---|
| Controller | Extend MageMe\WebForms\Controller\Adminhtml\Result\AbstractIntegrationSend (Controller/Adminhtml/Result/AbstractIntegrationSend.php, @api). Its constructor takes Controller\Adminhtml\Result\IntegrationSend\Context as the only argument: take it as your first constructor argument and pass it on. Implement integrationCode() and skipReason(ResultInterface $result): ?string; override integrationLabel() for the service name in messages and payload() for a JSON payload. Its ADMIN_RESOURCE is MageMe_WebForms::send_to_integrations. |
| Grid action class | Extend MageMe\WebForms\Ui\Component\Result\Listing\MassActions\IntegrationSubAction (@api). It needs no code of its own. A subclass takes MageMe\WebForms\Ui\Component\Result\Listing\MassActions\IntegrationSubAction\Context as its first constructor argument; its own dependencies can come before the UI component context, and it passes both contexts to the parent. |
| Listing XML | integration item with code, label (the menu item, for example Send to HubSpot) and url (your controller's route); settings/label is the service name the confirmation names, as in "Send the selected submissions to HubSpot?". |
| Visibility | Hidden for an admin role without Edit Result; disabled when the integration is off for the form, or when isAccountConfigured() is false for the grid's store view (IntegrationSubAction::isDisabled()). |
The HubSpot add-on's action, from view/adminhtml/ui_component/webforms_result_listing.xml of
MageMe_WebFormsHubspot:
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="hubspot"
class="MageMe\WebFormsHubspot\Ui\Component\Result\Listing\MassActions\SubActions\Hubspot">
<argument name="data" xsi:type="array">
<item name="integration" xsi:type="array">
<item name="code" xsi:type="string">hubspot</item>
<item name="label" xsi:type="string" translate="true">Send to HubSpot</item>
<item name="url" xsi:type="string">webformshubspot/result/ajaxSendData</item>
</item>
</argument>
<settings>
<type>hubspot</type>
<label translate="true">HubSpot</label>
</settings>
</action>
</massaction>
</listingToolbar>
</listing>
Form settings
The add-on keeps its per-form settings in its own columns on mm_webforms_form and adds a section to the form
settings through the modifier pool. Ui\Component\Form\Form\Modifier\Integration\AbstractIntegrationSettings is
the base the MageMe add-ons use: implement integrationCode(), accountKey(), fieldsetNames() and
buildMeta() (AbstractIntegrationSettings.php). Its constructor takes one MageMe\WebForms\Ui\Component\Form\Form\Modifier\Integration\IntegrationSettings\Context: take it as your first constructor argument and pass it on. It adds a Refresh Lists button that fetches the service's lists (pipelines,
groups, owners) into a cache; opening the form never calls the service. How to write such a list: Remote option lists.
When a form is imported or duplicated, the core observer Observer\Integration\RemapOnImport
(etc/events.xml) points every key from getFieldIdKeys() and every row of getSerializedMappings() at
the new form's field ids, on the form and on each store view override, in one save. An add-on needs no observer
of its own for this.
Required form settings
Your integration may need a setting filled in while it's on for a form. Add a rule to the admin
etc/adminhtml/di.xml. WebForms then blocks saving the form while the integration is on and the setting is empty.
When the required setting is a select, the form also shows a notice under it. The Klaviyo add-on's rule (excerpt):
<type name="MageMe\WebForms\Model\Form\AddonSettings\RequiredWhenEnabled">
<arguments>
<argument name="rules" xsi:type="array">
<item name="klaviyo_track_event" xsi:type="array">
<item name="integration" xsi:type="string">Klaviyo</item>
<item name="toggle" xsi:type="string">Track</item>
<item name="gate" xsi:type="array">
<item name="enabled" xsi:type="string">is_klaviyo_enabled</item>
<item name="track" xsi:type="string">klaviyo_endpoint</item>
</item>
<item name="required" xsi:type="array">
<item name="klaviyo_event" xsi:type="string">Event</item>
</item>
<item name="watch" xsi:type="string">klaviyo_</item>
</item>
</argument>
</arguments>
</type>
| Key | What it holds |
|---|---|
integration | The integration's name in the message |
toggle | The label of the switch that turns it on |
gate | The form columns that must all be on for the rule to apply |
required | Each required column and its label |
watch | The prefix of the integration's columns: a change to any of them counts as a change to the integration |
The message reads "%1 needs %2 for %3. Set %2, then save again.", with the integration, the required setting and the switch.
When the rule applies:
- Only to saves in the form editor. Saves by an import, a duplicate or the API skip the check.
- Only to a save that turns the integration on or changes one of its settings. A form already saved without the setting is left alone until someone edits one of its integration settings.
- Only when its columns exist. A rule whose columns don't exist, because its add-on isn't installed, is dropped.
Example
A minimal add-on with the code northstar_crm. Global etc/di.xml:
<?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\Model\Integration\HandlerPool">
<arguments>
<argument name="handlers" xsi:type="array">
<item name="northstar_crm" xsi:type="object">Northstar\WebFormsCrm\Model\Integration\CrmHandler\Proxy</item>
</argument>
</arguments>
</type>
<type name="MageMe\WebForms\Model\Integration\DefinitionPool">
<arguments>
<argument name="definitions" xsi:type="array">
<item name="northstar_crm" xsi:type="object">Northstar\WebFormsCrm\Model\Integration\CrmDefinition</item>
</argument>
</arguments>
</type>
</config>
The definition, assuming the module added the columns is_northstar_crm_enabled and
northstar_crm_email_field_id to mm_webforms_form:
<?php
declare(strict_types=1);
namespace Northstar\WebFormsCrm\Model\Integration;
use MageMe\WebForms\Api\Data\FormInterface;
use MageMe\WebForms\Api\IntegrationDefinitionInterface;
class CrmDefinition implements IntegrationDefinitionInterface
{
public function getCode(): string
{
return CrmHandler::CODE;
}
public function isEnabledFor(FormInterface $form): bool
{
return (bool)$form->getData('is_northstar_crm_enabled');
}
public function getFieldIdKeys(): array
{
return ['northstar_crm_email_field_id'];
}
public function getSerializedMappings(): array
{
return [];
}
}
The handler, shaped like the Zapier add-on's (MageMe_WebFormsZapier, Model/Integration/ZapierHandler.php):
<?php
declare(strict_types=1);
namespace Northstar\WebFormsCrm\Model\Integration;
use MageMe\WebForms\Api\Data\IntegrationMessageInterface;
use MageMe\WebForms\Api\Data\ResultInterface;
use MageMe\WebForms\Api\Exception\IntegrationRejectedException;
use MageMe\WebForms\Api\FieldRepositoryInterface;
use MageMe\WebForms\Api\IntegrationHandlerInterface;
use MageMe\WebForms\Model\Integration\IdempotencyKey;
use Magento\Framework\HTTP\Client\CurlFactory;
use RuntimeException;
class CrmHandler implements IntegrationHandlerInterface
{
public const CODE = 'northstar_crm';
private const ENDPOINT = 'https://crm.northstar-supply.test/api/leads';
public function __construct(
private readonly CurlFactory $curlFactory,
private readonly FieldRepositoryInterface $fieldRepository,
private readonly IdempotencyKey $idempotencyKey
) {
}
public function handle(IntegrationMessageInterface $message, ResultInterface $result): void
{
$form = $result->getForm();
if (!$form->getData('is_northstar_crm_enabled')) {
return;
}
$emailFieldId = (int)$form->getData('northstar_crm_email_field_id');
if ($emailFieldId === 0) {
return;
}
$field = $this->fieldRepository->getById($emailFieldId, $message->getStoreId());
$email = $field->getValueForIntegration(
$result->getFieldArray()[$emailFieldId] ?? null,
(int)$result->getId()
);
$curl = $this->curlFactory->create();
$curl->setTimeout(10);
$curl->addHeader('Expect', '');
$curl->addHeader('Idempotency-Key', $this->idempotencyKey->get(self::CODE, (int)$result->getId()));
$curl->post(self::ENDPOINT, ['email' => $email, 'submission' => (int)$result->getId()]);
$status = $curl->getStatus();
if ($status === 422) {
throw new IntegrationRejectedException('Northstar CRM refused the lead', $status);
}
if ($status >= 400) {
throw new RuntimeException('Northstar CRM answered HTTP ' . $status, $status);
}
}
}
What's next
- CLI, cron and queues: run the consumer and read the queue's state.
- Events reference:
webforms_form_import,webforms_form_duplicateand the other events an add-on can observe. - Events, plugins and registries: the other registries add-ons fill, such as notification variables and extra answer rows.