1

I'm using Sprout Forms V3 on Craft 3. I'm trying to handle the submit within a controller. This choice is made to add a custom logic, to implement a Google reCAPTCHA (as the official Sprout's plugin isn't working).

This is the JS part:

grecaptcha.ready(function() {
    // Verify reCAPTCHA
    grecaptcha.execute(recaptchaSiteKey, { action: 'contactForm' }).then(function(token) {
        // Send the token to the server for verification
        var data = {
            token: token,
            action: 'contactForm',
            formData: $form.serialize()
        };
        data[csrfTokenName] = csrfTokenValue;
        fetch('/actions/utilities-module/captcha', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then(data => {
            console.log(data);
            if (data === true) {
                console.log('success');
            } else {
                console.log('error');
            }
        });
    });
});

and the controller part:

public function actionIndex()
{
    // Check CSRF
    $this->requirePostRequest();

    // Call cURL to POST request
    $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(array(
        'secret' => getenv('GOOGLE_RECAPTCHA_SECRET_KEY'),
        'response' => Craft::$app->getRequest()->getParam('token')
    )));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response, true);

    // Verify the response 
    if ($response["success"] && $response["action"] == 'contactForm' && $response["score"] >= 0.9) {

        // Process the form
        $formData = Craft::$app->getRequest()->getParam('formData');
        $response = Craft::$app->runAction('sprout-forms/entries/save-entry', [
            'handle' => 'contact',
            'submission' => $formData
        ]);

        if (!$response['success']) {
            return $this->asJson(false);
        }

        return $this->asJson(true);

    } else {
        return $this->asJson(false);
    }
}

The issue here is that it's always failing. Looks like the Craft::$app->runAction() is missing something to process.

Any idea what's wrong?

1 Answer 1

2

Upgrading to the latest versions will likely resolve any issues with the default implementation. There was a bug in the timing of our javascript that was resolved in 3.13.20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.