Created
June 1, 2021 20:40
-
-
Save ivanfgm/b0d04cc68b6b7fbb996335afa523c55b to your computer and use it in GitHub Desktop.
Validate a recaptcha token with wordpress plugin contact form 7, useful when integrating with a custom frontend.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Verificacion especial recaptcha - cf7 */ | |
add_filter('wpcf7_spam', function ($spam) { | |
if ($spam) { | |
return $spam; | |
} | |
$submission = WPCF7_Submission::get_instance(); | |
if ("" == trim($_POST['g-recaptcha-response'])) { | |
$spam = true; | |
$submission->add_spam_log([ | |
'agent' => 'custom_recaptcha_v3', | |
'reason' => "Empty 'g-recaptcha-response'", | |
]); | |
} else { | |
$token = $_POST['g-recaptcha-response']; | |
$secret = 'YOUR_RECAPTCHA_SECRET_KEY'; | |
// verify recaptcha response | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify"); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['secret' => $secret, 'response' => $token])); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
$response = curl_exec($ch); | |
curl_close($ch); | |
$responseArray = json_decode($response, true); | |
// validate response | |
if ($responseArray["success"] != true) { | |
$spam = true; | |
$error = empty($responseArray["error-codes"]) ? "Undefined error" : join(", ", $responseArray["error-codes"]); | |
$submission->add_spam_log([ | |
'agent' => 'custom_recaptcha_v3', | |
'reason' => "recaptcha error: $error", | |
]); | |
} | |
} | |
return $spam; | |
}, 10, 1); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment