PHP code example of jub / craft-google-recaptcha

1. Go to this page and download the library: Download jub/craft-google-recaptcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jub / craft-google-recaptcha example snippets


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
    	]
    ]
    
];

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

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

}

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;
    }
});

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.');
    }
});