juban / craft-google-recaptcha

Google reCAPTCHA for Craft CMS 3
https://plugins.craftcms.com/google-recaptcha
MIT License
3 stars 3 forks source link
cms craft craft-plugin craftcms google-recaptcha

Google reCAPTCHA plugin for Craft CMS 4

Stable Version Total Downloads Tests status

Google reCAPTCHA for Craft CMS enables to render and validate the reCAPTCHA widget. It is compatible with both API v2 and v3, including checkbox badge and invisible flavors.

Requirements

This plugin requires Craft CMS 4.0.0 or later and PHP 8.0.2 or later.

To use the plugin, you will need to get an API site key and secret key which you can configure here.

Installation

  1. Install with composer via composer require jub/craft-google-recaptcha from your project directory or from the Plugin Store section of the Control Panel.
  2. Install the plugin in the Craft Control Panel under Settings → Plugins, or from the command line via ./craft plugin/install google-recaptcha.

Configuration

Control Panel

You can manage configuration setting through the Control Panel by going to Settings → Google reCAPTCHA

Configuration file

You can create a google-recaptcha.php file in the config folder of your project and provide the settings as follow:

return [
    "version"           => 2, // Either 2 our 3
    "siteKey"           => '', // Site key
    "secretKey"         => '', // Secret key
    "size"              => 'normal', // (v2) normal, compact or invisible
    "theme"             => 'light', // (v2) light or dark
    "badge"             => 'bottomright', // (v2) bottomright, bottomleft or inline
    "actionName"        => 'homepage', // (v3) Default action name
    "scoreThreshold"    => 0.5 // (v3) Value between 0 and 1 to determine the minimum score to validate
    "actions"           => [ // (v3) List of actions with their associated score threshold value (see the template part below to know how to specify the action parameter in the render method)
        [
            'name'              => 'some_action_name',
            'scoreThreshold'    => 0.5
        ]
    ]

];

⚠️ Any value provided in that file will override the settings from the Control Panel.

Using Google reCAPTCHA

Display Google reCAPTCHA widget in template

You can integrate the Google reCAPTCHA widget in your Twig templates as follow:

{{ craft.googleRecaptcha.render() }}

The render method accept an optional parameter in which you can provide any HTML attributes to apply to the widget container (div for v2, hidden input for v3).
For example, to provide a container id, you can do:

{{ craft.googleRecaptcha.render({id: 'recaptcha-widget'}) }}

For v3 API, an action property can also be provided as follow:

{{ craft.googleRecaptcha.render({id: 'recaptcha-widget', action: 'some_action_name'}) }}

In that case, the score threshold to be used for that action can be defined in the "Actions Settings" part of the plugin control panel.

💡 For v2 API, you can provide a second boolean argument to the render method to trigger the instant rendering of the widget (ie. {{ craft.googleRecaptcha.render({ id: 'recaptcha-widget' }, true) }}). This is useful if you are working with views loaded through Ajax or Sprig calls and you need to refresh the widget.

Setting scripts extra attributes

In the first render parameter, scriptOptions special property can be used to add extra attributes to the generated scripts tags.

For example, to support Content Security Policy (CSP), assuming you are using the Sherlock security plugin, you could do the following:

{% set nonce = craft.sherlock.getNonce() %}
{{ craft.googleRecaptcha.render({scriptOptions: {'nonce': nonce}}) }}

Verify users submissions

To validate a user submission on server side, you can use the built-in method:

GoogleRecaptcha::$plugin->recaptcha->verify();

For example, in a module controller, you could do something like this:

public function actionSubmitForm() {
    if(GoogleRecaptcha::$plugin->recaptcha->verify()) {
        // Do something useful here
    }
    else {
        Craft::$app->session->setError('Looks like you are a robot!');
    }

}

Verify Guest Entries submissions

In order to add a reCAPTCHA verification when working with Craft Guest Entries plugin, you can do something like the following in a project module:

Event::on(SaveController::class, SaveController::EVENT_BEFORE_SAVE_ENTRY, function (SaveEvent $e) {
    /** @var Entry $submission */
    $submission = $e->entry;
    $submission->setScenario(Element::SCENARIO_LIVE);
    $submission->validate();
    // Check reCAPTCHA
    $isValid = GoogleRecaptcha::$plugin->recaptcha->verify();
    if (!$isValid) {
        $submission->addError('recaptcha', 'Please, prove you’re not a robot.');
        $e->isValid = false;
    }
});

Verify Contact Form submissions

In order to add a reCAPTCHA verification when working with Contact Form, you can do something like the following in a project module:

Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e) {
    /** @var Submission $submission */
    $submission = $e->sender;
    // Check reCAPTCHA
    $isValid = GoogleRecaptcha::$plugin->recaptcha->verify();
    if (!$isValid) {
        $submission->addError('recaptcha', 'Please, prove you’re not a robot.');
    }
});

Available events