{"id":2454,"date":"2022-08-22T18:42:32","date_gmt":"2022-08-22T16:42:32","guid":{"rendered":"https:\/\/www.h-hennes.fr\/blog\/?p=2454"},"modified":"2022-08-29T08:41:28","modified_gmt":"2022-08-29T06:41:28","slug":"prestashop-ajouter-un-captcha-sur-les-formulaires-de-vos-modules","status":"publish","type":"post","link":"https:\/\/www.h-hennes.fr\/blog\/2022\/08\/22\/prestashop-ajouter-un-captcha-sur-les-formulaires-de-vos-modules\/","title":{"rendered":"Prestashop : Ajouter un captcha sur les formulaires de vos modules"},"content":{"rendered":"\n<p>Afin d&rsquo;\u00e9viter le spam sur vos diff\u00e9rents formulaires je recommande en g\u00e9n\u00e9ral la mise en place d&rsquo;un captcha.<br>\u00c7a fait plusieurs ann\u00e9es que j&rsquo;\u00e9dite un module de captcha gratuit ( eicaptcha ) qui permets de l&rsquo;\u00e9viter sur les formulaires suivants :<\/p>\n<ul>\n<li>Formulaire de contact<\/li>\n<li>Formulaire de cr\u00e9ation de compte<\/li>\n<li>Formulaire d&rsquo;inscription \u00e0 la newsletter<\/li>\n<\/ul>\n<p>Celui-ci est disponible sur github et a \u00e9t\u00e9 t\u00e9l\u00e9charg\u00e9 des dizaines de milliers de fois : <a title=\"Captcha prestashop\" href=\"https:\/\/github.com\/nenes25\/eicaptcha\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/nenes25\/eicaptcha<\/a><br><br>Je viens de sortir une nouvelle version de ce module ( 2.4.0 ) qui rajoute une nouvelle fonctionnalit\u00e9 qui permets d&rsquo;utiliser la v\u00e9rification du captcha int\u00e9gr\u00e9e dans le module directement dans vos modules sp\u00e9cifiques.<br><br>Ceci \u00e0 travers 2 nouvelles m\u00e9thodes :<\/p>\n<p><strong>hookDisplayEicaptchaVerification<\/strong> : permets de r\u00e9cup\u00e9rer un template d&rsquo;affichage complet du captcha ( le captcha s&rsquo;affiche directement )<br><strong>hookActionGetEicaptchaParams<\/strong> : permets&nbsp; de r\u00e9cup\u00e9rer les param\u00e8tres n\u00e9cessaires \u00e0 l&rsquo;affichage du captcha ( il est possible de faire un affichage sp\u00e9cifique )<\/p>\n<p>Nous allons voir \u00e0 travers cet article comment le mettre en place \u00e0 travers la cr\u00e9ation d&rsquo;un module <strong>hhcustomform<\/strong><br>Le captcha sera impl\u00e9ment\u00e9 dans 2 situations<\/p>\n<ul>\n<li>Dans un formulaire sur la fiche produit<\/li>\n<li>Dans un controller front<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Captcha dans un formulaire sur la fiche produit<\/h3>\n\n\n\n<p>Pour afficher un formulaire sur la fiche produit nous allons utiliser le hook <em>displayProductExtraContent<\/em> qui va nous permettre de l&rsquo;afficher comme sur la capture ci-dessous, directement dans les onglets de la fiche produit.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image.png\"><img loading=\"lazy\" decoding=\"async\" width=\"607\" height=\"597\" src=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image.png\" alt=\"\" class=\"wp-image-2455\" srcset=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image.png 607w, https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-300x295.png 300w\" sizes=\"auto, (max-width: 607px) 100vw, 607px\" \/><\/a><figcaption>Captcha dans un formulaire de la fiche produit<\/figcaption><\/figure>\n\n\n<p>Voici le code du hook qui va permettre de g\u00e9rer l&rsquo;affichage du formulaire dans l&rsquo;onglet.<br>La fonction importante du module eicaptcha utilis\u00e9e est le hook displayEicaptchaVerification qui va permettre de r\u00e9cup\u00e9rer le contenu n\u00e9cessaire \u00e0 l&rsquo;affichage du captcha dans le formulaire.<\/p>\n\n\n<pre lang=\"php\">\/**\n     * [Front office] Affichage des contenus dans les onglets de la fiche produit\n     * @param array $params\n     * @return array\n     *\/\n    public function hookDisplayProductExtraContent(array $params)\n    {\n        $return = [];\n        $id_product = $params['product']-&gt;id;\n\n        $return[] = (new PrestaShop\\PrestaShop\\Core\\Product\\ProductExtraContent())\n            -&gt;setTitle($this-&gt;l('Customization'))\n            -&gt;setContent($this-&gt;getFormContent($id_product));\n\n        return $return;\n    }\n\n    \/**\n     * R\u00e9cup\u00e9ration du contenu du formulaire\n     * @param int $id_product\n     * @return string\n     *\/\n    protected function getFormContent(int $id_product): string\n    {\n        try {\n            $smartyParams = [\n                'id_product' =&gt; $id_product,\n                'formAction' =&gt; $this-&gt;context-&gt;link-&gt;getModuleLink(\n                    $this-&gt;name,\n                    'form'\n                ),\n                'backUrl' =&gt; $this-&gt;context-&gt;link-&gt;getProductLink(\n                    $id_product\n                ),\n            ];\n            \/\/Gestion de l'affichage du captcha\n            if ($eicaptcha = Module::getInstanceByName('eicaptcha')) {\n                $smartyParams['renderCaptcha'] = $eicaptcha-&gt;hookDisplayEicaptchaVerification(['module' =&gt; $this-&gt;name]);\n            }\n            $this-&gt;context-&gt;smarty-&gt;assign($smartyParams);\n            return $this-&gt;context-&gt;smarty-&gt;fetch(\n                'module:'.$this-&gt;name.'\/views\/templates\/hook\/displayProductExtraContent.tpl'\n            );\n\n        } catch (Exception $e) {\n            PrestaShopLogger::addLog(__METHOD__ . ' error : ' . $e-&gt;getMessage());\n        }\n\n        return '';\n    }\n<\/pre>\n\n\n\n<p>Voici le fichier tpl&nbsp;<em>views\/templates\/hook\/displayProductExtraContent.tpl<\/em> qui va g\u00e9rer l&rsquo;affichage du formulaire sur la fiche produit.<\/p>\n\n\n\n<pre escaped=\"true\" lang=\"smarty\"><div class=\"hhcustomform--form\">\n    <form name=\"hhcustomform--customization-form\" method=\"post\" action=\"{$formAction}\" class=\"form\">\n        <input type=\"hidden\" name=\"id_product\" value=\"{$id_product}\">\n        <input type=\"hidden\" name=\"submit_form\" value=\"1\">\n        <input type=\"hidden\" name=\"back\" value=\"{$backUrl}\">\n        <div class=\"form-group\">\n            <label for=\"name\">{l s='your name' mod='hhcustomform'}<\/label>\n            <input type=\"text\" name=\"name\" class=\"form-control\" placeholder=\"{l s='your name' mod='hhcustomform'}\" required=\"\">\n        <\/div>\n        <div class=\"form-group\">\n            <label for=\"email\">{l s='your email' mod='hhcustomform'}<\/label>\n            <input type=\"email\" name=\"email\" class=\"form-control\" placeholder=\"{l s='your email' mod='hhcustomform'}\" required=\"\">\n        <\/div>\n        <div class=\"form-group\">\n            <label for=\"customization\">{l s='your customization' mod='hhcustomform'}<\/label>\n            <textarea name=\"customization\" class=\"form-control\" rows=\"4\" required=\"\" placeholder=\"{l s='explain your requested customization' mod='hhcustomform'}\"><\/textarea>\n        <\/div>\n        {* On utilise la fonctionnalit\u00e9 de eicaptcha *}\n        {$renderCaptcha nofilter}\n        <button type=\"submit\" class=\"btn btn-primary\">{l s='Send' mod='hhcustomform'}<\/button>\n    <\/form>\n<\/div>\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Captcha dans un controller front<\/h3>\n\n\n\n<p>Dans cet exemple j&rsquo;utilise l&rsquo;autre fonctionnalit\u00e9 d&rsquo;affichage du captcha ( hookActionGetEicaptchaParams )<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><a href=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"511\" src=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1-1024x511.png\" alt=\"\" class=\"wp-image-2456\" srcset=\"https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1-1024x511.png 1024w, https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1-300x150.png 300w, https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1-768x383.png 768w, https:\/\/www.h-hennes.fr\/blog\/wp-content\/uploads\/2022\/08\/image-1.png 1250w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption>Affichage du captcha sur un controller front<\/figcaption><\/figure>\n\n\n\n<p>Voici le code du controller <em>controllers\/front\/form.php<\/em> qui va appeller le module.<\/p>\n\n\n\n<pre lang=\"php\" escaped=\"true\">\n<?php\nclass HhcustomformFormModuleFrontController extends ModuleFrontController\n{\n    \/**\n     * Manage Post Vars\n     *\/\n    public function postProcess()\n    {\n        if (Tools::isSubmit('submit_form')) {\n            parent::postProcess();\n            if (false !== $this->processCustomizationForm()) {\n                $this->success[] = $this->l('Thank you. Your message have been send with success');\n            } else {\n                $this->errors[] = $this->l('Error when sending your message');\n            }\n            $redirectUrl = Tools::getValue('back');\n            if ($redirectUrl) {\n                $this->redirectWithNotifications($redirectUrl);\n            }\n        }\n    }\n    \/**\n     * Generate controller breadCrumb\n     * @return array\n     *\/\n    public function getBreadcrumbLinks()\n    {\n        $breadcrumb = parent::getBreadcrumbLinks();\n        $breadcrumb['links'][] = [\n            'title' => 'form',\n            'url' => '#'\n        ];\n        return $breadcrumb;\n    }\n    \/**\n     * Traitement du formulaire\n     * @return bool|int\n     *\/\n    protected function processCustomizationForm()\n    {\n        \/\/Captcha validation\n        if ($eicaptcha = Module::getInstanceByName('eicaptcha')) {\n            if (!$eicaptcha->hookActionValidateCaptcha()) {\n                return false;\n            }\n        }\n        \/\/Traitement du formulaire \u00e0 impl\u00e9menter\n        return true;\n    }\n    \/**\n     * Controller Content\n     * @throws PrestaShopException\n     *\/\n    public function initContent()\n    {\n        parent::initContent();\n        $this->context->smarty->assign(\n            'formAction',\n            $this->context->link->getModuleLink($this->module->name, 'form')\n        );\n        \/\/R\u00e9cup\u00e9ration des param\u00e8tres du captcha pour affichage custom\n        if ($eicaptcha = Module::getInstanceByName('eicaptcha')) {\n            $this->context->smarty->assign('captchaParams', $eicaptcha->hookActionGetEicaptchaParams([]));\n        }\n        $this->setTemplate('module:hhcustomform\/views\/templates\/front\/form.tpl');\n    }\n}\n<\/pre>\n\n\n\n<p>Et voici le code du template d&rsquo;affichage associ\u00e9<\/p>\n\n\n\n<pre escaped=\"true\" lang=\"smarty\">{extends file='page.tpl'}\n{block name=\"content\"}\n    <div class=\"hhcustomform--form\">\n        <form name=\"hhcustomform--customization-form\" method=\"post\" action=\"{$formAction}\" class=\"form\">\n            <div class=\"form-group\">\n                <label for=\"name\">{l s='your name' mod='hhcustomform'}<\/label>\n                <input type=\"text\" name=\"name\" class=\"form-control\" placeholder=\"{l s='your name' mod='hhcustomform'}\" required=\"\">\n            <\/div>\n            <div class=\"form-group\">\n                <label for=\"email\">{l s='your email' mod='hhcustomform'}<\/label>\n                <input type=\"email\" name=\"email\" class=\"form-control\" placeholder=\"{l s='your email' mod='hhcustomform'}\" required=\"\">\n            <\/div>\n            <div class=\"form-group\">\n                <label for=\"customization\">{l s='your customization' mod='hhcustomform'}<\/label>\n                <textarea name=\"customization\" class=\"form-control\" rows=\"4\" required=\"\" placeholder=\"{l s='explain your requested customization' mod='hhcustomform'}\"><\/textarea>\n            <\/div>\n            {* On utilise la fonctionnalit\u00e9 de eicaptcha mais avec un formulaire qu'on d\u00e9fini comme on veut *}\n            <div class=\"form-group row\">\n                {if $captchaParams.captchaVersion == 2}\n                    <label class=\"col-md-3\">{l s='Captcha' mod='eicaptcha'}<\/label>\n                    <div class=\"col-md-9\">\n                        <div class=\"g-recaptcha\" data-sitekey=\"{$captchaParams.publicKey|escape:'html'}\" id=\"captcha-box\" data-theme=\"{$captchaParams.captchatheme}\"><\/div>\n                        <script src=\"https:\/\/www.google.com\/recaptcha\/api.js{if isset($captchaParams.captchaforcelang)}?hl={$captchaParams.captchaforcelang}{\/if}\" async=\"\" defer=\"\"><\/script>\n                    <\/div>\n                {else}\n                    <input type=\"hidden\" id=\"captcha-box-custom\" name=\"g-recaptcha-response\">\n                    <script src=\"https:\/\/www.google.com\/recaptcha\/api.js?render={$publicKey|escape:'html'}\"><\/script>\n                    <script>\n                        grecaptcha.ready(function () {ldelim}\n                            grecaptcha.execute('{$captchaParams.publicKey|escape:'html'}', {ldelim}action: 'contact'{rdelim}).then(function (token) {ldelim}\n                                var recaptchaResponse = document.getElementById('captcha-box-custom');\n                                recaptchaResponse.value = token;\n                                {rdelim});\n                            {rdelim});\n                    <\/script>\n                {\/if}\n            <\/div>\n            <button type=\"submit\" class=\"btn btn-primary\">{l s='Send' mod='hhcustomform'}<\/button>\n        <\/form>\n    <\/div>\n{\/block}\n\n<\/pre>\n\n\n\n<p>A travers ces diff\u00e9rents exemples vous pouvez donc voir qu&rsquo;il est relativement facile d&rsquo;ajouter un captcha sur n&rsquo;importe quel formulaire de vos modules \ud83d\ude42<br \/>Pour t\u00e9l\u00e9charger le module de captcha eicaptcha, ou signaler des probl\u00e8mes vous rendre directement sur github : <a title=\"Captcha prestashop\" href=\"https:\/\/github.com\/nenes25\/eicaptcha\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/nenes25\/eicaptcha<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Afin d&rsquo;\u00e9viter le spam sur vos diff\u00e9rents formulaires je recommande en g\u00e9n\u00e9ral la mise en place d&rsquo;un captcha.\u00c7a fait plusieurs ann\u00e9es que j&rsquo;\u00e9dite un module de captcha gratuit ( eicaptcha ) qui permets de l&rsquo;\u00e9viter sur les formulaires suivants : Formulaire de contact Formulaire de cr\u00e9ation de compte Formulaire d&rsquo;inscription \u00e0 la newsletter Celui-ci est [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[245],"tags":[260,483],"class_list":["post-2454","post","type-post","status-publish","format-standard","hentry","category-prestashop-2","tag-captcha","tag-prestashop-1-7","prestashop-1-4","prestashop-1-5","prestashop-1-6","prestashop-1-7","prestashop-1-7-2","prestashop-1-7-3","prestashop-1-7-4","prestashop-1-7-5","prestashop-1-7-6","prestashop-1-7-7","prestashop-1-7-8","prestashop-8-0","prestashop-8-1"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/posts\/2454","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/comments?post=2454"}],"version-history":[{"count":2,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/posts\/2454\/revisions"}],"predecessor-version":[{"id":2458,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/posts\/2454\/revisions\/2458"}],"wp:attachment":[{"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/media?parent=2454"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/categories?post=2454"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h-hennes.fr\/blog\/wp-json\/wp\/v2\/tags?post=2454"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}