hryvinskyi / magento2-privacy-consent-frontend
Consent checkboxes in Magento storefront forms (registration, contact, newsletter, product review, checkout), checked on the server and journaled, and the customer's consents page.
Package info
github.com/hryvinskyi/magento2-privacy-consent-frontend
Type:magento2-module
pkg:composer/hryvinskyi/magento2-privacy-consent-frontend
Requires
- php: ~8.1.0||~8.2.0||~8.3.0||~8.4.0||~8.5.0
- hryvinskyi/magento2-clock: ^1.0
- hryvinskyi/magento2-privacy-consent: ^1.0
- hryvinskyi/magento2-privacy-consent-api: ^1.0
- hryvinskyi/magento2-theme-assets: ^1.0
- magento/framework: *
- magento/module-checkout: *
- magento/module-contact: *
- magento/module-customer: *
- magento/module-newsletter: *
- magento/module-quote: *
- magento/module-review: *
- magento/module-sales: *
- magento/module-store: *
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
The storefront half of the privacy consent suite: consent checkboxes in the registration, contact, newsletter, product review and checkout forms, a server check that refuses a submission without a required consent, the journal entry for each box a shopper ticked, and a Privacy Consents page where a signed-in customer sees the state of each consent and withdraws an optional one. It implements no consent rule of its own. It calls the services of hryvinskyi/magento2-privacy-consent.
What it does for a store
-
Checkboxes in six forms. The consents the admin assigned to a form and a store view appear as checkboxes, unticked by default, in that form:
Form code Where it shows Admin label registrationThe register page, in the container form.additional.info.Customer registration contactThe contact page, in form.additional.info.Contact us reviewThe product page's review form, in form.additional.review.info.Product review newsletterThe footer, right after the newsletter form. Newsletter subscription (footer) newsletter_accountThe newsletter page of the customer account, inside its form. Newsletter subscription (customer account) checkoutThe checkout, above Place Order, in every payment method's block. Checkout (place order) -
The text and the link. A consent's text is printed as text, escaped. One
{{link}}…{{/link}}span becomes a link to the consent's CMS page of the current store view, opened in a new tab (target="_blank" rel="noopener"). A span with no CMS page shows as its plain words. -
A server check before the form's action. A submission that lacks a required consent of its form never reaches the form's action. The visitor is back on the form, with what they entered, and one message:
Please accept: <consent title>, <consent title>.The check guards the storefront form posts, so it works with JavaScript off and for a browser or a script that posts the form. It does not guard the API paths named under Limits. -
A box ticked after the action succeeded is journaled. The row is written once the account exists, the message was sent, the subscription was saved, the review was saved or the order was placed. A refused submission, and a submission the form's own action refused (a wrong captcha, an existing account, an invalid e-mail address), records nothing. An unticked optional box records nothing. A consent that the form does not show in the store view is ignored when posted and never recorded.
-
The version is the one shown. Each box posts the id of the version it showed (
privacy_consent[<consent code>]=<version id>), so a consent reworded while the page was open is recorded under the wording the person saw. -
Pages stay cacheable. The checkbox markup holds no personal data and no per-visitor state, so it is the same for every visitor of a store view and the page stays in the full-page cache. A box is never pre-ticked on a cached page; only a refused submission's own ticks come back, and only on a page that cannot be cached (see Limits). The block carries one cache tag for its form,
hpc_consent_<form code>, which the core drops whenever a consent that is shown in that form is saved, deactivated or deleted or its linked CMS page changes, so a cached page never keeps an old wording. -
The footer box submits without JavaScript. It is printed beside the footer form and joined to it by the HTML
formattribute, so the browser submits it with the form and no script moves it. -
A convenience script for required boxes.
privacy-consent.js, rendered external and deferred throughhryvinskyi/magento2-theme-assets, stops a submit while a required box is unticked, shows the box'sThis is a required field.message and focuses the first such box. It is optional: the server check is the rule. -
Checkout. The consents of the checkout form show above Place Order in each payment method's block, none ticked. Place Order is blocked while a required box of the selected payment method is unticked, with
Please accept: <title>.. The ticked boxes travel with the order in the payment'sprivacy_consentsextension attribute (a consent code and the shown version id). The server refuses an order without a required consent before it is placed, for signed-in customers and guests, and journals the consents of a placed order with the order's increment id. -
The consents page. A signed-in customer opens My Account > Privacy Consents (
privacyconsent/consents). For every consent the store view shows, the page gives the state (Given, Withdrawn or Not given), and the version, form and date of the customer's latest record, with the date shown in the store view's timezone. An optional consent the customer gave has a Withdraw button. A visitor who is not signed in is sent to the sign-in page. -
Withdrawal. The button journals a
withdrawnrecord, then runs each withdrawal action of the consent, and showsYou withdrew your consent to "<title>".The customer returns to the page of this store they came from, or else to the consents page. A required consent has no button, and a forged request to withdraw one, one already withdrawn or one never given writes nothing and shows the reason. -
The newsletter action. The
newsletter_unsubscribewithdrawal action unsubscribes the customer from the newsletter of the store view where they withdrew. -
Every unsubscribe is a withdrawal. When a newsletter subscriber's status changes from subscribed to unsubscribed on the account page, through the e-mail link, in the admin or through the API, each consent that is shown in the subscriber's store view, lists the
newsletter_unsubscribeaction and was last given by that subscriber gets awithdrawnrecord with the form codeunsubscribe. A subscriber that belongs to a customer account is journaled twice over: for the account, by what the account gave, and for its e-mail address alone, by what the address gave as a guest. A subscription made as a guest and linked to an account later therefore gets itswithdrawnrecord for the address, naming no customer, and the account gets none unless it gave the consent itself. The visitor's client address is stored only when the unsubscribe is made on the storefront (the account page or the e-mail link); an unsubscribe made in the admin, through the API or by a scheduled job stores none, because the address would be the staff member's or the server's. No withdrawal action runs: the unsubscribe already happened. After a withdrawal on the consents page the account's latest record is alreadywithdrawn, so the unsubscribe it causes writes nothing more for the account; the e-mail address gets its ownwithdrawnrecord when it last gave the consent as a guest. -
Failures never reach the shopper. A failure to journal a ticked box or a withdrawal is written to
var/log/hryvinskyi/privacy_consent.logwith the form, the exception's class and its code, and never an e-mail address or a client address. The form's own action, the placed order and the visitor's page are not affected.
Requirements
- Magento Open Source or Adobe Commerce 2.4.x with a Luma-based theme. The suite is built and tested on 2.4.9.
- PHP 8.1 to 8.5.
hryvinskyi/magento2-privacy-consent-api^1.0,hryvinskyi/magento2-privacy-consent^1.0 andhryvinskyi/magento2-theme-assets^1.0.- The platform's Customer, Contact, Newsletter, Review, Checkout, Quote, Sales and Store modules.
Installation
Run from the Magento root. hryvinskyi/magento2-privacy-consent-pack installs this package with the rest of the suite.
composer require hryvinskyi/magento2-privacy-consent-frontend bin/magento module:enable Hryvinskyi_PrivacyConsentApi Hryvinskyi_Clock Hryvinskyi_ClientAddress Hryvinskyi_PrivacyConsent Hryvinskyi_Base Hryvinskyi_HeadTagManager Hryvinskyi_ThemeAssets Hryvinskyi_PrivacyConsentFrontend bin/magento setup:upgrade bin/magento setup:di:compile # production mode only bin/magento setup:static-content:deploy -f # production mode only bin/magento cache:flush
A store that merges, bundles or caches RequireJS files regenerates that bundle after the install, or the checkout loads the old place-order action without the consents (see Limits).
Verify on the storefront: create a consent in the admin (Customers > Privacy Consents > Consents), assign it to the Customer registration form and a store view, and open the register page of that store view. The consent shows as an unticked checkbox with its text. After signing in, My Account lists Privacy Consents.
Configuration
None of its own. The package reads two settings:
| Path | Default | Effect |
|---|---|---|
hryvinskyi_privacy_consent/general/enabled |
1 |
Settable down to a store view. When 0, the store view shows no checkbox and the server asks for nothing and journals nothing. |
newsletter/general/active |
the platform's | The two newsletter boxes exist only while the platform's newsletter is on: the footer block is printed under this setting, and the account page's newsletter form is the platform's own. |
The consents, their store views and forms, and the address mode are managed in the admin (hryvinskyi/magento2-privacy-consent-admin-ui).
Limits
- Checkout covers one way of placing an order. The consents are sent by the platform's place-order action of the checkout page, which calls
savePaymentInformationAndPlaceOrder. These orders carry none and are neither checked nor journaled: a GraphQL place order (a Hyvä checkout or a headless storefront),PUT /V1/carts/mine/orderandPUT /V1/guest-carts/:cartId/order, multishipping, a payment method's own review page before the order is placed, and an instant (one-click) purchase or a payment button that places the order through its own controller. A store that uses any of them keeps required checkout consents off: a required checkout consent refuses an order that arrives without the attribute. - Codes sent with
savePaymentInformation, the call that places no order, are never read. - The server check guards the storefront form posts only. The REST and GraphQL ways to create a customer account, subscribe to the newsletter, send the contact form and post a review (for example
POST /V1/customersand the GraphQL account, newsletter, contact and review mutations) run no consent check and journal no ticked box. Keep required consents of those forms only on stores that do not expose those paths to the public, or accept that scripted requests skip them. - Hyvä themes are not supported. The checkboxes render in Luma-based themes, and the checkout part is Knockout.
- A merged or minified RequireJS bundle must be rebuilt after install. The checkout adds a mixin to
Magento_Checkout/js/action/place-order. A store that merges, bundles or caches RequireJS files (a JS merge module, or a bundle kept by a cache) serves the old file until it is rebuilt, and then places orders without the consents. - A guest cannot withdraw a consent. There is no account to sign in to. A guest's request goes through the store's privacy contact.
- A guest review is journaled without a subject. It has no customer id and no e-mail address, and its reference is the review's id. A signed-in customer's review names the customer.
- Restoring ticks after a refusal. Only the registration, contact and customer-account newsletter forms remember the ticks of a refused submission, because only they return to a page the store does not cache. A remembered tick is kept for 300 seconds. After a refusal for a missing consent, the boxes come back ticked only on a page that the full-page cache does not store, and the ticks are spent by the first time the form's boxes are printed, on whichever page that is: the register and contact pages are such pages only while the platform's captcha module is installed, because it adds a block that cannot be cached. Without that module those pages are cached, and the boxes come back unticked. After the form's own errors (a wrong captcha, an existing account) the boxes come back unticked. The footer newsletter and review forms return to a cached page, so their refusal keeps no ticks and returns with the message only.
- A consent's link points at its CMS page by identifier. The core refuses an active consent whose page is missing from one of its store views, and a page save that would take such a store view away. A page disabled after the consent was saved is not refused: its link then gives "page not found".
- The newsletter boxes appear only while the newsletter is enabled (
newsletter/general/active). The account page asks only when the submission would subscribe a customer who is not subscribed now: saving the page with the box unticked while subscribed, or unsubscribing, is never refused. - A subscription saved by another action journals no newsletter row. A registration that asks for a newsletter subscription, and an admin's subscription, write none, because only the footer form and the account page journal a
givenrow for the newsletter forms. - Imported rows are not on the customer's consents page. A row imported from an external journal names no consent, so it is no consent's latest record. It is visible to the admin, in the journal and in the customer's Consents tab, and in a data export of the subject, not on this page.
- Withdrawing does not delete anything. The consent's earlier records stay, because they are the evidence.
- One refusal message per request when another check refuses first. The consent check skips a request another observer already refused. A captcha observer that runs after it does not look at that, so both messages can show.
- A form submitted by script skips the client check (
form.submit()does not raise a submit event) and meets the server check. - The script is requested once for each checkbox block. A product page, which holds the review form and the footer form, prints two identical deferred tags; the script binds once.
- The empty-page message
You have not given any consent yet.shows only when the store view shows no consent at all. A customer who gave nothing sees each consent as Not given. - A referer that points at another site or the home page counts as no referer. The customer returns to the consents page then.
The checkbox markup
For each consent the block prints:
<div class="privacy-consents" data-privacy-consents="<form code>"> <div class="field choice privacy-consent required"> <input type="checkbox" class="checkbox" name="privacy_consent[<consent code>]" value="<current version id>" id="privacy-consent-<form code>-<consent code>" form="<form id, footer only>" data-privacy-consent-required="1" aria-describedby="privacy-consent-<form code>-<consent code>-error"> <label class="label" for="privacy-consent-<form code>-<consent code>">…the text…</label> <div class="mage-error" id="privacy-consent-<form code>-<consent code>-error" hidden>This is a required field.</div> </div> </div>
The element id holds the form code, because a product page holds the review form and the footer form, and both can show one consent. The checkout's boxes are named privacy_consent[<payment method>][<consent code>], with the payment method in the id too, because every payment method's block renders the same consents.
Registrations
| Where | What |
|---|---|
| Storefront route | frontName privacyconsent: consents/index (GET) and consents/withdraw (POST, with the form key and the consent's code). |
| Layout handles | default (the footer newsletter box), customer_account_create, contact_index_index, catalog_product_view, newsletter_manage_index, checkout_index_index, customer_account (the account navigation link) and privacyconsent_consents_index. |
| Templates | checkboxes.phtml, consents.phtml, and the Knockout template web/template/checkout/consents.html. |
| Scripts | js/privacy-consent.js; the checkout's js/view/checkout-consents, js/model/{checkout-consents,checkout-consent-rules,consents-assigner,consents-validator,place-order-mixin}; a RequireJS mixin on Magento_Checkout/js/action/place-order. |
| Predispatch observers (storefront) | controller_action_predispatch_customer_account_createpost, …_contact_index_post, …_review_product_post, …_newsletter_subscriber_new, …_newsletter_manage_save. Each is a virtual type of Observer\RefuseMissingConsent with its own binding. |
| Success hooks | Observer on customer_register_success; observer on review_save_after; plugin on Magento\Contact\Model\MailInterface; plugin on Magento\Newsletter\Model\SubscriptionManagerInterface (subscribe and subscribeCustomer); plugins on Magento\Checkout\Api\PaymentInformationManagementInterface and GuestPaymentInformationManagementInterface (before refuses, after journals). |
| Observer (global) | newsletter_subscriber_save_after: Observer\RecordUnsubscribeWithdrawal. |
| Extension attribute | privacy_consents (Hryvinskyi\PrivacyConsentApi\Api\Data\PostedConsentInterface[]) on Magento\Quote\Api\Data\PaymentInterface. |
| Checkout plugins area | The two checkout plugins are in the global etc/di.xml, because the storefront places the order through the REST API, which runs in another area than the storefront. |
| Layout processor | Magento\Checkout\Block\Onepage::layoutProcessors item privacyConsents, in the storefront etc/frontend/di.xml, because the platform declares that argument in its storefront file and an item in the global file would be replaced. |
| Form list | Six FormProvider virtual types and their items in the core's FormPool argument providers. |
| Withdrawal action | newsletter_unsubscribe in the core's WithdrawalActionPool argument actions. |
| Cache tag | hpc_consent_<form code>, declared by Block\ConsentCheckboxes through IdentityInterface, one for the form the block shows. |
| Log | The core's channel, var/log/hryvinskyi/privacy_consent.log. |
The package registers no table, cron job, command or ACL resource.
Extension points
A form on the storefront is built from five pieces: a binding class, a virtual type of the check observer with its events.xml entry, a FormProvider item, a layout entry for the checkbox block, and a success hook that calls the recorder. These are the pieces of the shipped registration form.
1. A binding class (Model/Form/Binding/RegistrationBinding.php) says which requests are submissions of the form and how the form refuses one: it keeps the input the way the form keeps it on its own errors, adds the message and returns the redirect the form uses on its own errors. It never touches the response.
class RegistrationBinding implements FormBindingInterface { public const FORM_CODE = 'registration'; public function __construct( private readonly SubmittedRequest $submitted, private readonly Session $session, private readonly ManagerInterface $messages, private readonly RedirectFactory $redirects ) { } public function getFormCode(): string { return self::FORM_CODE; } public function appliesTo(RequestInterface $request): bool { return $this->submitted->isPost($request); } public function refuse(RequestInterface $request, Phrase $message): ResultInterface { $this->messages->addErrorMessage($message); $this->session->setCustomerFormData($this->submitted->values($request)); return $this->redirects->create()->setPath('customer/account/create', ['_secure' => true]); } }
2. A virtual type of the check observer and its event, in the storefront etc/frontend/di.xml and etc/frontend/events.xml. The event is controller_action_predispatch_<the form's full action name>:
<virtualType name="Hryvinskyi\PrivacyConsentFrontend\Observer\RefuseMissingRegistrationConsent" type="Hryvinskyi\PrivacyConsentFrontend\Observer\RefuseMissingConsent"> <arguments> <argument name="binding" xsi:type="object">Hryvinskyi\PrivacyConsentFrontend\Model\Form\Binding\RegistrationBinding</argument> <argument name="rememberTicks" xsi:type="boolean">true</argument> </arguments> </virtualType>
Set rememberTicks to true only when the form's refusal returns the visitor to a page the store does not cache (the registration, contact and customer-account newsletter forms). It defaults to false: a form that returns to a cached page keeps no ticks in the session.
<event name="controller_action_predispatch_customer_account_createpost"> <observer name="hryvinskyi_privacy_consent_registration" instance="Hryvinskyi\PrivacyConsentFrontend\Observer\RefuseMissingRegistrationConsent"/> </event>
The observer skips a request another observer already refused, a store view with consents off and a request the binding does not apply to. Otherwise it asks the core's required-consent check; on a missing consent it remembers the posted ticks (when the form's rememberTicks is on), stops the action and renders the binding's refusal.
3. A form provider item, in the global etc/di.xml (the admin offers exactly the forms in this list). The label is read through __() when it is shown, so a new form adds its label to the package's i18n files by hand.
<virtualType name="Hryvinskyi\PrivacyConsentFrontend\Model\Form\RegistrationForm" type="Hryvinskyi\PrivacyConsentFrontend\Model\Form\FormProvider"> <arguments> <argument name="code" xsi:type="string">registration</argument> <argument name="label" xsi:type="string">Customer registration</argument> </arguments> </virtualType> <type name="Hryvinskyi\PrivacyConsent\Model\Form\FormPool"> <arguments> <argument name="providers" xsi:type="array"> <item name="registration" xsi:type="object">Hryvinskyi\PrivacyConsentFrontend\Model\Form\RegistrationForm</item> </argument> </arguments> </type>
4. A layout entry for the checkbox block in the form's handle, inside a container the form prints. Never add cacheable="false": the markup is the same for every visitor. A box printed outside its form takes a form_id argument, the id of the form it joins.
<referenceContainer name="form.additional.info"> <block class="Hryvinskyi\PrivacyConsentFrontend\Block\ConsentCheckboxes" name="privacy.consent.registration"> <arguments> <argument name="form_code" xsi:type="string">registration</argument> <argument name="view_model" xsi:type="object">Hryvinskyi\PrivacyConsentFrontend\ViewModel\ConsentCheckboxes</argument> <argument name="asset_renderer" xsi:type="object">Hryvinskyi\ThemeAssets\Api\AssetRendererInterface</argument> </arguments> </block> </referenceContainer>
5. A success hook that calls the recorder with the subject once the form's action succeeded. It acts only for its own full action name, so another action that fires the same event records nothing:
class RecordRegistrationConsent implements ObserverInterface { private const ACTION = 'customer_account_createpost'; public function execute(Observer $observer): void { $customer = $observer->getEvent()->getData('customer'); if (!$this->action->isFullName(self::ACTION) || !$customer instanceof CustomerInterface) { return; } $this->recorder->record( RegistrationBinding::FORM_CODE, $this->subjects->forCustomer((int)$customer->getId(), (string)$customer->getEmail()), null ); } }
SubmissionRecorder::record(formCode, subject, reference) reads the ticked boxes, the store view and the client address from the current request. It journals a form at most once per request, does nothing when no box was ticked, and never throws. The subject comes from the core's ConsentSubjectFactoryInterface (forCustomer, forGuest or anonymous). The action name compares in lower case, the way Magento names an action's events.
The checkout does not post a request parameter, so its hook builds a submission from the payment's privacy_consents and calls the core's recorder directly.
Add a withdrawal action
A withdrawal action implements Hryvinskyi\PrivacyConsentApi\Api\WithdrawalActionInterface and is registered in the core's pool. This is the shipped newsletter action:
class NewsletterUnsubscribe implements WithdrawalActionInterface { public const CODE = 'newsletter_unsubscribe'; public function __construct(private readonly SubscriptionManagerInterface $subscriptions) { } public function getCode(): string { return self::CODE; } public function getLabel(): Phrase { return __('Unsubscribe from the newsletter'); } public function execute(int $customerId, int $storeId, ConsentInterface $consent): void { $this->subscriptions->unsubscribeCustomer($customerId, $storeId); } }
<type name="Hryvinskyi\PrivacyConsent\Model\Withdrawal\WithdrawalActionPool"> <arguments> <argument name="actions" xsi:type="array"> <item name="newsletter_unsubscribe" xsi:type="object">Hryvinskyi\PrivacyConsentFrontend\Model\Withdrawal\NewsletterUnsubscribe</item> </argument> </arguments> </type>
The admin lists the action's label under When Withdrawn of each consent. An action that throws is logged and does not undo the withdrawal record.
Place the consents block on another account page
The block on the consents page is self-contained: a Magento\Framework\View\Element\Template with the template Hryvinskyi_PrivacyConsentFrontend::consents.phtml and one argument, view_model = Hryvinskyi\PrivacyConsentFrontend\ViewModel\CustomerConsents. It needs no parent, no child and no handle. The layout that places it must set cacheable="false", because the block prints a signed-in customer's own states. The withdraw form posts to privacyconsent/consents/withdraw. The account link is the block customer-account-navigation-privacy-consents-link (a Magento\Customer\Block\Account\SortLink, sort order 31), which another package can replace or hide by that name.
Tests
Run from the Magento root.
- Unit:
vendor/bin/phpunit -c app/code/Hryvinskyi/PrivacyConsentFrontend/phpunit.xml.dist. - Browser scripts (Node's own test runner):
node --test app/code/Hryvinskyi/PrivacyConsentFrontend/Test/Js/*.mjs. - Integration: the platform's harness in
dev/tests/integration, against its own database, one run at a time.cd dev/tests/integration && php -d memory_limit=4G ../../../vendor/bin/phpunit -c phpunit.xml ../../../app/code/Hryvinskyi/PrivacyConsentFrontend/Test/Integration. A controller test posts to one URL for each test method. - Browser flows:
Test/E2e/, run with the@hryvinskyi/magento2-e2epackage from the shop'se2e/directory (npm testthere). The specs sign in to the admin, create their own required consents with unique codes, and check the admin's journal and the customer's Consents tab. A consent that the journal names cannot be deleted, so the specs deactivate theirs. - Static analysis: PHPStan 2.x at level 10 with the package's
phpstan.neon.dist(phpstan analyse -c app/code/Hryvinskyi/PrivacyConsentFrontend/phpstan.neon.dist --level=10), andvendor/bin/phpcs --standard=app/code/Hryvinskyi/PrivacyConsentFrontend/phpcs.xml.dist app/code/Hryvinskyi/PrivacyConsentFrontend.
Translations
The storefront wording ships in en_US and 25 more locales: the official languages of the European Union, Norwegian Bokmål and Ukrainian. The translations are machine-made; have them read by a native speaker before a store relies on them, and override a phrase in a theme or a language pack. The consent's own text is data the admin enters for each store view and is not translated by the package.