How to integrate Recaptcha in Prestashop in 3 steps

How to integrate Recaptcha in Prestashop in 3 steps

Prestashop is one of the most used ecommerce on the internet BUT the contact form has no protection again the spam. Of course you can buy an additional plugin but I will explain how to integrate a spam protection without paying. You have to create and configure an account, change 2 sources. You can make it in 30 mn or less.

Here is a howto step by step for prestashop 1.6 (I don’t know about prestashop 1.7 but I imagine it should be similar).

1 Setup your Google reCAPTCHA if you don’t have it

https://www.google.com/recaptcha/intro/index.html

Note the key and the secret key

You have to configure it and put your domain name.

2  Change the contact-form.tpl

First you have to change the contact form (client side) contact-form.tpl should be in your theme. Open an editor and search the submit botton

For me it is like that

 <div class="submit">
 <button type="submit" name="submitMessage" id="submitMessage" class="button"><span>{l s='Send'}<i class="icon-chevron-right right"></i></span></button>
 </div>
 </form>

 

Just above add few lines of code. Replace key by your key

 <script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="key"></div>

 

That should look like that

<div>
 <script src='https://www.google.com/recaptcha/api.js'></script>
 <div class="g-recaptcha" data-sitekey="key"></div>
</div>

 <div class="submit">
 <button type="submit" name="submitMessage" id="submitMessage" class="button"><span>
{l s='Send'}
<i class="icon-chevron-right right"></i></span>
</button>
 </div>
 </form>

3 Change ContactControler.php

If you don’t have this source in override\controllers\front copy it from controllers\front

Then you have to add few lines to check if the captcha is ok or not

search the postProcess() function it should be at the begining (2nd function) and add

  if (Tools::isSubmit('submitMessage')) {
 $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
 $file_attachment = Tools::fileAttachment('fileUpload');
 $message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags.
 $id_order = (int)$this->getOrder();
 if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
 $this->errors[] = Tools::displayError('Invalid email address.');
// add the 2 lines from here
 } elseif (!($gcaptcha = (int)(Tools::getValue('g-recaptcha-response')))) {
 $this->errors[] = Tools::displayError('Captcha error');
// to here

33 réflexions sur « How to integrate Recaptcha in Prestashop in 3 steps »

  1. It lets people send without completing the captcha.
    Prestashop 1.6.1.4

    1. Correction:
      Either if I complete the captcha or not, it never sends, but it gives a success alert, instead of an error, so people might think the message was sent, when it wasn’t.

      1. It should work.

        On my PS 1.6.0.14, not checking the captcha results in a « captacha error » message on the form.

        If it does never send, maybe your host (typically OVH) has disabled your script emails capabilities (mail() php function).

        Also check your code in contactcontroller.php (better to use override/controller/front/contactontroller.php that the core one, as specified)

        Syntax may be correct but logic corrupted with brackets.

        my code looks like

        if (!($from = trim(Tools::getValue(‘from’))) || !Validate::isEmail($from))
        $this->errors[] = Tools::displayError(‘Invalid email address.’);
        // add the 2 lines from here – note the (non-)bracketing
        elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’))))
        $this->errors[] = Tools::displayError(‘Montrez que vous n etes pas une machine en cochant la derniere case’);

        elseif (!$message)
        $this->errors[] = Tools::displayError(‘The message cannot be blank.’);

      2. You probably solved your problem, but for someone else it might be helful. If you override your controller, you should clear your cache as well. That was helpful for me. After changes go to Administration Panel -> Advanced Parameters -> Performance parameters and then Clear Smarty Cache.

  2. Hello,

    For me it worked on the contact-form.
    But i want to add it also to the backoffice admin login form and it seems i cannot make it work. I add all the configuration but it always gives me an error even after i click the reCaptcha.
    I edited AdminLoginController.php all way around so i could not tell you exactly where i teste the code because i tried to put it all over the public function processLogin()

  3. Thank you!
    It also works on Prestashop 1.5.4
    Just had to remove the brackets as Ben has said before.

  4. I followed your steps. Unfortunately there is no repatcha to click, the contact form didn’t change but when I try to submit email it shows error with « captcha error » … Any idea what went wrong?

  5. Only works if the main controller file is modified, not works if copied to override.

    1. Thank you for all your explanations!
      same here, only working on main controller. PS v.1.6.1.8

  6. I added code to contact-form.tmp and ContactController.php (in controllers/front, nothing in overrides) so code now looks like:

    $this->errors[] = Tools::displayError(‘Invalid email address.’);
    } elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
    $this->errors[] = Tools::displayError(‘Captcha error’);
    elseif (!$message)

    However, I get error: Parse error: syntax error, unexpected ‘elseif’ (T_ELSEIF) in /home2/userName/public_html/controllers/front/ContactController.php on line 47

    1. the last row of your code you don’t have a closing « } », that’s why it give you the error and also after the condition « elseif (!$message) » you need to add output.

      1. Am not familiar with PHP. I simply copy pasted the code as per instructions. So I should paste following?

        } elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
        $this->errors[] = Tools::displayError(‘Captcha error’); }

        Can you give example of what you mean by « add output? »

        Thanks.

      2. if (!($from = trim(Tools::getValue(‘from’))) || !Validate::isEmail($from)) {
        $this->errors[] = Tools::displayError(‘Invalid email address.’);
        } elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
        $this->errors[] = Tools::displayError(‘Captcha error’);
        } elseif (!$message) {
        $this->errors[] = Tools::displayError(‘The message cannot be blank.’);
        }

        as you can see the gcaptcha is now between the first if and the second elseif that already are in the file.
        I would recommend to insert it exactly like this

        elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
        $this->errors[] = Tools::displayError(‘Captcha error’);
        }
        right after the closing « } » of the if condition so you would have

        if(condition){
        do this and that
        } and here you add the code i wrote higher and it should work.

        1. I get another error if I copy-paste above:
          Parse error: syntax error, unexpected ’email’ (T_STRING) in /home2/user/public_html/controllers/front/ContactController.php on line 50

          I commented out some code so I can revert. Page now looks like following:
          public function postProcess()
          {
          if (Tools::isSubmit(‘submitMessage’))
          {
          $extension = array(‘.txt’, ‘.rtf’, ‘.doc’, ‘.docx’, ‘.pdf’, ‘.zip’, ‘.png’, ‘.jpeg’, ‘.gif’, ‘.jpg’);
          $file_attachment = Tools::fileAttachment(‘fileUpload’);
          $message = Tools::getValue(‘message’); // Html entities is not usefull, iscleanHtml check there is no bad html tags.
          /* if (!($from = trim(Tools::getValue(‘from’))) || !Validate::isEmail($from))
          $this->errors[] = Tools::displayError(‘Invalid email address.’);
          } elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
          $this->errors[] = Tools::displayError(‘Captcha error’); }
          elseif (!$message)
          $this->errors[] = Tools::displayError(‘The message cannot be blank.’); */
          if (!($from = trim(Tools::getValue(‘from’))) || !Validate::isEmail($from)) {
          $this->errors[] = Tools::displayError(‘Invalid email address.’);
          } elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’)))) {
          $this->errors[] = Tools::displayError(‘Captcha error’);
          } elseif (!$message) {
          $this->errors[] = Tools::displayError(‘The message cannot be blank.’);
          }
          elseif (!Validate::isCleanHtml($message))
          $this->errors[] = Tools::displayError(‘Invalid message’);
          Continued with original code…

      3. bogdan.ghita90 add this skype address and send me your contactcontroller.php

        Also Juliettwest add it and i can help you with it.

  7. Hi,

    Does someone know how to do this with prestashop 1.7.2.2? The contactcontroller.php file looks totally different, so know I don’t know where to add the code :).

    Thanks in advance for the help!

    Regards,
    Juliëtte

  8. With Bogdan’s help, I was able to overcome the errors. In Ps 1.6.0.14, your ContactController.php should look like following:

    public function postProcess()
    {
    if (Tools::isSubmit(‘submitMessage’))
    {
    $extension = array(‘.txt’, ‘.rtf’, ‘.doc’, ‘.docx’, ‘.pdf’, ‘.zip’, ‘.png’, ‘.jpeg’, ‘.gif’, ‘.jpg’);
    $file_attachment = Tools::fileAttachment(‘fileUpload’);
    $message = Tools::getValue(‘message’); // Html entities is not usefull, iscleanHtml check there is no bad html tags.
    if (!($from = trim(Tools::getValue(‘from’))) || !Validate::isEmail($from))
    $this->errors[] = Tools::displayError(‘Invalid email address.’);
    elseif (!($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’))))
    $this->errors[] = Tools::displayError(‘Captcha error’);
    elseif (!$message)
    $this->errors[] = Tools::displayError(‘The message cannot be blank.’);
    elseif (!Validate::isCleanHtml($message))
    $this->errors[] = Tools::displayError(‘Invalid message’);
    elseif (!($id_contact = (int)Tools::getValue(‘id_contact’)) || !(Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))))
    $this->errors[] = Tools::displayError(‘Please select a subject from the list provided. ‘);
    elseif (!empty($file_attachment[‘name’]) && $file_attachment[‘error’] != 0)
    $this->errors[] = Tools::displayError(‘An error occurred during the file-upload process.’);
    elseif (!empty($file_attachment[‘name’]) && !in_array(Tools::strtolower(substr($file_attachment[‘name’], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment[‘name’], -5)), $extension))
    $this->errors[] = Tools::displayError(‘Bad file extension’);
    else
    {

  9. Here is for 1.7 :

    /public_html/themes/YOUR_THEME_NAME/modules/contactform/views/templates/widget/contactform.tpl

    Add this:

    Right before

    10:39 AM
    /public_html/modules/contactform

    Add this;

    if (($gcaptcha = (int)(Tools::getValue(‘g-recaptcha-response’))) == 0) {
    $this->errors[] = $this->trans(‘Please complete reCaptcha’, array(), ‘Admin.Login.Notification’);
    echo ‘Please compete the reCaptcha’;
    }

    Right after:

    $notifications = false;
    if (Tools::isSubmit(‘submitMessage’)) {

  10. Ok :)) so for the first step:
    Add this:

    Right before

    I added some spaces because when i post it, it removes the formatting

  11. Ok :)) so for the first step:
    Add this:
    Apparently i cannot add div format. So add the div provided by google reCaptcha with your public key.

    Right before
    The footer where your submit button is, it has a name of submitMessage
    I hope you understand because i cannot write the code directly it strips the formatting

  12. Thanks for the nice quick steps

    Works good, but remember to delete the class_index.php file in the cache folder after you Change ContactControler.php

    Always forget about that one….

  13. Hello,
    please can you advice me? I changed codes in both files. I can see captcha in contact form but it let me send message without completing captcha. I have prestashop v. 1.6.0.6.

    1. Hi everybody,
      I’m not a developer, but I can do some change myself in the code, if I have the right infrmarmations.

      to Hhennes:
      how you have completed the work in Prestashop with new informations?
      Where did you add code to check if the captcha answer is valid?

      to everybody:
      is this way finally working?
      in other words: is this tutorial completed and usefull to solve the problem?
      Thanks
      Michele

  14. Thank you very much for this tutorial!
    I have been looking for a solution to verify Recaptcha for a long time. Everything I tried failed. Meanwhile, I kept being the victim of .ru spam every day.
    I hope this is the final solution.

  15. I used Kris method on prestashop 1.6.1.18 with an override controller and contact-form.tpl. It’s working fine; however i had to clear cache AND remove the file cache/class_index.php.

  16. BTW how can it work only with public key? Don’t we also need to add secret key somewhere?
    Cheers

Les commentaires sont clos.

Les commentaires sont clos.