Skip to content

Instantly share code, notes, and snippets.

@tomaskavalek
Created September 13, 2022 12:29
Show Gist options
  • Save tomaskavalek/d2b9bf0f946fe26504c4daaaed77b75b to your computer and use it in GitHub Desktop.
Save tomaskavalek/d2b9bf0f946fe26504c4daaaed77b75b to your computer and use it in GitHub Desktop.
WordPress HappyForms reCAPTCHA – solution for free version of HappyForms plugin
<?php
/**
* Google reCAPTCHA for WordPress HappyForms
*
* @author Tomas Kavalek <[email protected]>
* @version 1.0.0
*/
class HappyForms_Recaptcha
{
/**
* @var string reCAPTCHA key
*/
private $key;
/**
* @var string reCAPTCHA secret
*/
private $secret;
/**
* @param string $key
* @param string $secret
*/
public function __construct(string $key, string $secret)
{
$this->key = $key;
$this->secret = $secret;
add_filter('happyforms_validate_submission', [$this, 'validateSubmission'], 10, 3);
add_action('wp_head', [$this, 'recaptchaLoader'], 10, 0);
add_action('happyforms_form_open', [$this, 'recaptchaHolder'], 10, 0);
}
/**
* @param $isValid
* @param $request
* @param $form
* @return bool
*/
public function validateSubmission($isValid, $request, $form)
{
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
} else {
$captcha = false;
}
$remoteIp = $_SERVER['REMOTE_ADDR'] ?? '';
if (false !== $captcha) {
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $this->secret . "&response=" . $captcha . "&remoteip=" . $remoteIp
);
$response = json_decode($response);
return $response->success && $isValid;
}
return false;
}
/**
* @return void
*/
public function recaptchaLoader()
{
?>
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $this->key; ?>"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('<?php echo $this->key; ?>', {action: 'validate_captcha'})
.then(function (token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
<?php
}
/**
* @return void
*/
public function recaptchaHolder()
{
?>
<div class="" id="happyforms-recaptcha" data-happyforms-type="recaptcha" data-happyforms-id="recaptcha" data-happyforms-required="">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"/>
</div>
<?php
}
}
new HappyForms_Recaptcha('KEY', 'SECRET');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment