Categories
Uncategorized

How to make reCaptcha v2/ Invisible API call to verify request with PHP 7.1.x

Make sure that you have listed the domain you are using to run this piece of php code, under the list of allowed domains in your corresponding recaptcha module in google.
Enter
recaptcha.php

 $secret, 'response' => $_POST['recaptcha']);
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) {
        error_log('https request to Google API failed!');
        echo '{"message" : "Sorry! Something went wrong."}';
    } else {
        $result = json_decode($result, true);
        if (!$result) {
            error_log(json_last_error_msg());
            echo '{"message" : "Sorry! Something went wrong."}';
        } else {
            if ($result["success"] === true) {
                echo '{"message" : "OK"}';
            } else {
                error_log("error : " . $result["challenge_ts"]
                    . "hostname : " . $result["hostname"]
                    . "error-codes : " . $result["error-codes"]);
                echo '{"message" : "Sorry! Something went wrong."}';
            }
        }
    }
}