Did you know that adding Google reCaptcha in Magento 2 is just a matter of including an external PHP library? Today we worked on aclient requirement to include Google reCaptcha in the contact forms of his Magento online store. Captcha is an essential feature for any and every contact form in your website since it keeps the spammers and bots away from our inbox. Do you have a similar requirement? Read on to know the DIY way of achieving this. Alternatively, keep your hands off the code and hire a developer from VelanApps.
We used a PHP library “google/recaptcha” inorder to do the server side validation of the submitted Captcha. Not just this instance, but in most cases when clients want an extra feature, do remember that you could always achieve this with an external PHP library. We usually include external PHP libraries in our projects in order to make our development process quicker, easier and simply put, it’s a waste of time reinventing the wheel right?
STEPS TO INCLUDE EXTERNAL PHP LIBRARIES IN MAGENTO 2 PROJECTS:
1. Identify the PHP library name in the Packagist repository.
2. Most of the PHP libraries are hosted in the Packagist repository which we can easily include in our Magento 2 project.
3. For our purpose, we will use the google/recaptcha library from the Packagist:
4. We will be using composer to include the reCaptcha module in our project. Note the name of the package that we have highlighted in the above image.
5. Now, the only things you have to do is:
- Open the terminal
- Navigate to your Magento 2 project’s root folder location
- Enter this command: composer require google/recaptcha
6. That’s it! Wait for the installation to complete. Once the process in completed, you will note the following line added to the composer.json file present in the root folder location of you Magento 2 project:
7. The inclusion of the reCaptcha line indicates that the PHP library is successfully included in your Magento 2 project.You will note that the googlereCaptcha module gets added to the vendor folder:
Voila! Now we have the Google Recaptcha External module successfully included in our project. We can call it using the following code in any file (be it a Block, Model or Controller):
$recaptcha = new \ReCaptcha\ReCaptcha($secretKey);
Hope you found this tutorial easy to follow! We keep posting a lot of helpful tutorials that can help developers as well store owners work with their Magento Online Stores. If you ever need to hire a developer or hire a website designer, be sure to hit us up because we’ve got the crème-de-la-crème of Magento developers.
You can consult with VelanApps if you’re looking to:
- hire a developer
- hire digital marketing experts
- hire website designers
Just fill in this quick form if you want to hire a developer. Takes just 2 minutes and you can instantly connect with our devs!