| 1 |
<?php |
| 2 |
|
| 3 |
namespace Depicter\Services; |
| 4 |
|
| 5 |
use Averta\WordPress\Utility\JSON; |
| 6 |
use Depicter\GuzzleHttp\Exception\GuzzleException; |
| 7 |
use Depicter\Utility\Sanitize; |
| 8 |
|
| 9 |
class GoogleRecaptchaV3 |
| 10 |
{ |
| 11 |
public function verify( $token ) { |
| 12 |
|
| 13 |
$secret = \Depicter::options()->get( 'google_recaptcha_secret_key', '' ); |
| 14 |
if ( empty( $secret ) ) { |
| 15 |
return false ; |
| 16 |
} |
| 17 |
|
| 18 |
$options = [ |
| 19 |
'form_params' => [ |
| 20 |
'secret' => $secret, |
| 21 |
'response' => $token |
| 22 |
] |
| 23 |
]; |
| 24 |
|
| 25 |
try{ |
| 26 |
$response = \Depicter::remote()->post( 'https://www.google.com/recaptcha/api/siteverify', $options ); |
| 27 |
if ( $response->getStatusCode() != 200 ) { |
| 28 |
return [ |
| 29 |
'success' => false, |
| 30 |
'data' => [], |
| 31 |
'message' => __( 'Could not contact google to verify the request', 'depicter' ) |
| 32 |
]; |
| 33 |
} |
| 34 |
$content = $response->getBody()->getContents(); |
| 35 |
$result = JSON::decode( $content, true ); |
| 36 |
|
| 37 |
$scoreThreshold = \Depicter::options()->get( 'google_recaptcha_score_threshold', 0.6 ); |
| 38 |
|
| 39 |
if ( !empty( $result['score'] ) && ( $result['score'] > Sanitize::float( $scoreThreshold ) ) ) { |
| 40 |
return [ |
| 41 |
'success' => true, |
| 42 |
'data' => [ |
| 43 |
'host' => $result['hostname'] ?? '' |
| 44 |
], |
| 45 |
/* translators: recaptcha score */ |
| 46 |
'message' => sprintf( __( 'Recaptcha challenge passed successfully. [%s]', 'depicter' ), $result['score'] ) |
| 47 |
]; |
| 48 |
|
| 49 |
} else { |
| 50 |
$failMessage = \Depicter::options()->get( 'google_recaptcha_fail_message','' ) . "[" .( $result['score'] ?? '0' ) . "]"; |
| 51 |
|
| 52 |
return [ |
| 53 |
'success' => false, |
| 54 |
'data' => [ |
| 55 |
'score' => $result['score'] ?? 0, |
| 56 |
'host' => $result['hostname'] ?? '' |
| 57 |
], |
| 58 |
'message' => $failMessage |
| 59 |
]; |
| 60 |
} |
| 61 |
} catch( GuzzleException $e ){ |
| 62 |
return [ |
| 63 |
'success' => false, |
| 64 |
'message' => $e->getMessage() |
| 65 |
]; |
| 66 |
} |
| 67 |
|
| 68 |
} |
| 69 |
} |
| 70 |
|