| 1 |
<?php |
| 2 |
|
| 3 |
namespace King_Addons; |
| 4 |
|
| 5 |
if (!defined('ABSPATH')) { |
| 6 |
exit; |
| 7 |
} |
| 8 |
|
| 9 |
class Verify_Google_Recaptcha |
| 10 |
{ |
| 11 |
public function __construct() |
| 12 |
{ |
| 13 |
add_action('wp_ajax_king_addons_verify_recaptcha', [$this, 'king_addons_verify_recaptcha']); |
| 14 |
add_action('wp_ajax_nopriv_king_addons_verify_recaptcha', [$this, 'king_addons_verify_recaptcha']); |
| 15 |
} |
| 16 |
|
| 17 |
public function king_addons_verify_recaptcha() |
| 18 |
{ |
| 19 |
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { |
| 20 |
wp_send_json_error(['message' => 'Invalid request method.']); |
| 21 |
} |
| 22 |
|
| 23 |
if (!isset($_POST['nonce']) || !check_ajax_referer('king-addons-js', 'nonce', false)) { |
| 24 |
wp_send_json_error(['message' => 'Invalid nonce.']); |
| 25 |
} |
| 26 |
|
| 27 |
$recaptcha_response = sanitize_text_field($_POST['g-recaptcha-response'] ?? ''); |
| 28 |
if (empty($recaptcha_response)) { |
| 29 |
wp_send_json_error(['message' => 'Missing reCAPTCHA response.']); |
| 30 |
} |
| 31 |
|
| 32 |
$is_valid_recaptcha = $this->check_recaptcha($recaptcha_response); |
| 33 |
|
| 34 |
if ($is_valid_recaptcha[0] && $is_valid_recaptcha[1] >= get_option('king_addons_recaptcha_v3_score_threshold')) { |
| 35 |
wp_send_json_success(array( |
| 36 |
'message' => 'Recaptcha Success', |
| 37 |
'score' => $is_valid_recaptcha[1] |
| 38 |
)); |
| 39 |
} else { |
| 40 |
wp_send_json_error(array( |
| 41 |
'message' => 'Recaptcha Error', |
| 42 |
'score' => $is_valid_recaptcha[1], |
| 43 |
'results' => [ |
| 44 |
$is_valid_recaptcha[0], |
| 45 |
$is_valid_recaptcha[1] >= get_option('king_addons_recaptcha_v3_score_threshold') |
| 46 |
] |
| 47 |
)); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
public function check_recaptcha($recaptcha_response) |
| 52 |
{ |
| 53 |
$secret_key = get_option('king_addons_recaptcha_v3_secret_key'); |
| 54 |
$remote_ip = $_SERVER['REMOTE_ADDR']; |
| 55 |
|
| 56 |
$response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', array( |
| 57 |
'body' => array( |
| 58 |
'secret' => $secret_key, |
| 59 |
'response' => $recaptcha_response, |
| 60 |
'remoteip' => $remote_ip |
| 61 |
) |
| 62 |
)); |
| 63 |
|
| 64 |
if (is_wp_error($response)) { |
| 65 |
return [false, 0]; |
| 66 |
} |
| 67 |
|
| 68 |
$decoded_response = json_decode(wp_remote_retrieve_body($response), true); |
| 69 |
|
| 70 |
if (!is_array($decoded_response)) { |
| 71 |
return [false, 0]; |
| 72 |
} |
| 73 |
|
| 74 |
$score = isset($decoded_response['score']) ? (float) $decoded_response['score'] : 0.0; |
| 75 |
|
| 76 |
if (!empty($decoded_response['success'])) { |
| 77 |
return [true, $score]; |
| 78 |
} else { |
| 79 |
return [false, $score]; |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
new Verify_Google_Recaptcha(); |