For arlanix/notification 1.0.1
Add a protocol
A protocol is a way of delivering notifications. Email, Telegram, Slack and Discord are four protocols, and each is a separate module. Your module can add another protocol, such as Microsoft Teams or SMS. The subscription form then offers it in Delivered by. Each subscription has one address in its protocol's terms: one email address, one chat or one webhook.
The class
Implement Arlanix\Notification\Model\Protocol\ProtocolInterface. It has the following methods:
| Method | What it does |
|---|---|
deliver(Endpoint $endpoint, Digest $digest): void |
Sends one notification, or several as one digest. The digest gives $digest->isSingle(), entries(), total() and severity(). Throw an exception on any failure, and the delivery is retried. The operator sees the message of a DeliveryException exactly as you write it, so say what to fix and include no secret. For any other exception, the error is logged and the operator sees a generic message. |
address(Endpoint $endpoint): string |
Returns the one place the subscription delivers to, as one value. A topic accepts one subscription per address. Return case-insensitive values, such as email addresses, in lower case. Return a secret, such as a webhook URL, as a hash, because the table stores the address unencrypted. |
describe(Endpoint $endpoint): string |
Returns one line for the grid and the log, with no secret. It must never throw. |
validate(Endpoint $endpoint): string[] |
Returns the reasons why the endpoint cannot be used, or an empty array when it can. When there are reasons, saving the subscription fails and shows them. |
setupProblem(Endpoint $endpoint): ?string |
Returns what prevents the protocol from sending to this endpoint before anything is tried, or null when it can send. An example is a bot token that is set neither for the store nor on the subscription. Delivery, Send test message and the warning on save all call it. |
When the service asks you to wait (HTTP 429), throw Arlanix\Notification\Model\Protocol\RateLimitedException($phrase, $retryAfter), with $retryAfter in seconds. When you do not give it, the wait is 60 seconds. The wait is at most one hour. The delivery, and the subscription's digests after it, wait that long. During the first day after the message was published, the wait does not use up an attempt.
Endpoint gives you the subscription's settings and secrets:
setting('endpoint/<code>_…')returns a setting, typed by its normaliser.secret(…)returns a secret, decrypted.
Arlanix\Notification\Model\Render\PlainTextRenderer writes a subject and a body from a digest. Its maxLength argument fits the text into a chat's limit. When the text is cut, the digest ends with a line that says how many more messages the Message Log has, so no message is dropped without notice. If your protocol supports formatting, write your own renderer.
Post over HTTP
If your protocol posts to an API or a webhook, use Arlanix\Notification\Model\Protocol\Http\HttpClientInterface::postJson($url, $body, $timeout). It returns the answer whatever its status. When no answer arrives, it throws a DeliveryException that names the host but never the URL, because the URL can contain a secret.
The returned HttpResponse gives the following:
- The status, and
isRateLimited()for a429. - The body, and
json()to decode it. - The headers, for example
header('Retry-After'). retryAfter(), how long the service asks you to wait. It reads theRetry-Afterheader, in seconds or as a date, orretry_afterin the JSON body. It returnsnullwhen the service gives no wait time.
Registering it
Register the protocol in your module's etc/di.xml. Give it a code that starts with a lower-case letter and contains only lower-case letters and digits. Also register its settings.
A secret is not a setting. List it under secrets. A secret is stored encrypted on the subscription and is never sent back to the form.
<type name="Arlanix\Notification\Model\Protocol\ProtocolPool">
<arguments>
<argument name="protocols" xsi:type="array">
<item name="teams" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Microsoft Teams</item>
<item name="protocol" xsi:type="object">Vendor\NotificationTeams\Model\TeamsProtocol</item>
<item name="icon" xsi:type="string">Vendor_NotificationTeams::images/teams.svg</item>
<item name="sortOrder" xsi:type="number">30</item>
<item name="secrets" xsi:type="array">
<item name="webhook" xsi:type="string">endpoint/teams_webhook_url</item>
</item>
</item>
</argument>
</arguments>
</type>
<virtualType name="Arlanix\Notification\Model\Subscription\SettingPool">
<arguments>
<argument name="settings" xsi:type="array">
<item name="endpoint/teams_channel" xsi:type="array">
<item name="normalise" xsi:type="object">Arlanix\Core\Model\Settings\Normaliser\StringNormaliser</item>
</item>
</argument>
</arguments>
</virtualType>
Every setting and secret of a protocol has a path that starts with endpoint/<code>_. When a subscription is saved, the settings of other protocols are deleted. So a webhook typed for Teams does not stay after the subscription switches to email.
A normaliser must not throw, because every registered normaliser runs on every save.
The form
Add the fields in view/adminhtml/ui_component/arlanix_notification_subscription_form.xml, in the endpoint fieldset. Give each field variants with your protocol's code, so that the form shows the field only for that protocol:
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="endpoint">
<field name="teams_channel" formElement="input" sortOrder="100">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="variants" xsi:type="array">
<item name="0" xsi:type="string">teams</item>
</item>
</item>
</argument>
<settings>
<label translate="true">Channel</label>
<dataType>text</dataType>
</settings>
</field>
</fieldset>
</form>
A secret field posts its value under the same name as the secret, such as teams_webhook_url. When the field is left blank, the stored secret is kept. The form receives has_teams_webhook_url, which is true when a secret is stored.
For a secret field, use the component Arlanix_Core/js/form/element/secret. It masks the value and never fills it in. To show that a secret is stored, import ${ $.provider }:data.endpoint.has_teams_webhook_url into its showStoredNotice, and put the text in its storedNotice.
The configuration
Some settings are needed once for the whole store, such as a bot token. Put them in a group of the arlanix_notification section in system.xml, under the same ACL resource, Arlanix_Notification::config. Make setupProblem() report when such a setting is missing.
For a secret in the configuration, use Magento\Config\Model\Config\Backend\Encrypted in system.xml, and as the default's backend_model in config.xml. The configuration then decrypts the value when it reads it. So use the value as you get it, and do not decrypt it again.
Trying it
The four protocols that come with Multichannel Store Notifications are examples to follow. They are arlanix/module-notification-smtp, -telegram, -slack and -discord in vendor/.
To test your protocol, follow these steps:
- Save a subscription delivered by your protocol.
- Click Send test message on the subscription. See Subscriptions. One message goes straight to
deliver(), without the queue and the log. - Check the result:
- If
setupProblem()returns a problem, sending stops and the problem is shown. - Otherwise, the notice above the grid says that the message was sent. If sending failed, the notice shows the message of a
DeliveryExceptionexactly as written, or a generic message for any other exception. The row's Last delivery keeps the result.
- If
- To test the full path, click Publish test message in a topic's row. See Topics. The message goes through the queue, as a module's message does, to every subscription of the topic that receives all severities.