Search by

deimon / nette-recaptcha

deimon

Google reCAPTCHA v2 (checkbox) and v3 (score) for Nette Forms. Server-side verification over cURL (works with allow_url_fopen=0), any number of protected forms per page, client-side validation via netteForms.

Package info

gitlab.com/deimon/nette-recaptcha

Issues

pkg:composer/deimon/nette-recaptcha

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

v1.1.0 2026-11-26 13:55 UTC

This package is not auto-updated.

Last update: 2026-11-27 08:13:40 UTC


README

Latest version Pipeline License

Google reCAPTCHA v2 (checkbox) and v3 (score) for Nette Forms.

  • Server-side verification over cURL – works on hosting with allow_url_fopen=0. Uses the official google/recaptcha library.
  • Any number of protected forms on one page. Every widget writes its token into the hidden input of its own form, so a form is never validated against another form's widget.
  • Client-side validation through netteForms. Submitting a form with an unticked checkbox shows the form's error message right away, for that form only.
  • Stricter checks than a plain success flag: the hostname the token was issued for, the token age and, for v3, the expected action and the minimal score.
  • The JavaScript ships with the package (assets/recaptcha.js). You can print it with the {recaptchaScript()} Latte function, so there is nothing to download or copy by hand.
  • v2 and v3 can be used together on one page. Content loaded by Naja is initialized automatically.

Requirements

  • PHP 8.4+ with ext-curl
  • nette/forms 3.2+, nette/di 3.2+, nette/http 3.3+
  • optional: latte/latte 3.1+ (for {recaptchaScript()}), tracy/tracy (logs failed verifications)

Installation

composer require deimon/nette-recaptcha

Configuration

Create the keys in the reCAPTCHA admin console. v2 and v3 each need their own key pair. Configure only the versions you use.

extensions:
	recaptcha: Deimon\ReCaptcha\DI\ReCaptchaExtension

recaptcha:
	v2:
		siteKey: '...'
		secretKey: '...'
	v3:
		siteKey: '...'
		secretKey: '...'

	minScore: 0.5          # default v3 threshold: 0.0 = bot … 1.0 = human
	checkHostname: true    # token must be issued for the host of the current request
	challengeTimeout: 300  # max. token age in seconds (0 = not checked)
	requestTimeout: 10     # cURL timeout in seconds
	logFailures: true      # failed verifications → log/recaptcha.log (needs Tracy)
	latte: true            # registers {recaptchaScript()} (needs Latte)
	loading: interaction   # when the browser loads Google's script: interaction | immediate (see below)

For local development you can use Google's v2 test keys. They always pass, and the hostname check is skipped for them automatically. Google provides no test keys for v3.

Usage

Form

// v2 – "I'm not a robot" checkbox
$form->addReCaptcha('captcha', 'Please confirm that you are not a robot.');

// v3 – invisible; action name and optional per-form threshold
$form->addReCaptchaV3('captcha', 'Bot verification failed, please try again.', action: 'contact', minScore: 0.6);

The message is shown when the check fails. With a translator set on the form, it is translated like any other form message. The captcha value is never included in $form->getValues().

$form->addReCaptcha('captcha', 'Please confirm that you are not a robot.')
	->setTheme('dark')     // light | dark
	->setSize('compact');  // normal | compact

Template

Render the control like any other one. v3 renders just a hidden input.

{form contactForm}
	...
	{input captcha}
	<div n:ifcontent class="error">{inputError captcha}</div>
	{input send}
{/form}

JavaScript

Load netteForms and the bundled script once per page, typically at the end of @layout.latte:

<script src="{$basePath}/js/netteForms.min.js"></script>  {* vendor/nette/forms/src/assets/netteForms.min.js *}
{recaptchaScript()}

{recaptchaScript()} prints assets/recaptcha.js inline. If your Content Security Policy uses nonces, pass the nonce: {recaptchaScript($nonce)}.

When Google's script is loaded (privacy)

By default (loading: interaction) Google's api.js is not loaded on page load. It is loaded on the first interaction with a protected form – a click, focus or key press. Visitors who never use a form send nothing to Google. The v2 checkbox appears a moment after the first interaction. A v3 form submitted before the script is ready is held back and submitted as soon as the token is available.

Use loading: immediate (or $form['captcha']->setLoading('immediate') for one form) to load the script on page load, e.g. when the v2 checkbox has to be visible right away.

Google reCAPTCHA processes personal data (IP address, device and interaction data). Mention it in your privacy policy.

Other ways to include the script:

  • Vite / bundler: import it by a path to vendor/, e.g. import '../vendor/deimon/nette-recaptcha/assets/recaptcha.js'.
  • Static file: copy vendor/deimon/nette-recaptcha/assets/recaptcha.js into your public directory, for example with a Composer post-update-cmd script.

If you insert forms with an AJAX library other than Naja, initialize them after inserting the HTML:

NetteReCaptcha.init(element);   // renders new widgets / binds new v3 forms
NetteReCaptcha.reset(form);     // resets v2 widgets, e.g. after an AJAX submit failed

How it works

v2v3
HTMLwidget placeholder + the control's hidden inputthe control's hidden input
Browserwidget writes its token into the hidden input of its own form; netteForms checks the :filled ruleon submit grecaptcha.execute(action) fills the hidden input, then the form is submitted again
Servertoken verified with Google: success, hostname, agetoken verified with Google: success, hostname, age, action, score

Google accepts every token only once. The verification result is therefore cached for the request, so validating a form repeatedly is safe.

Failed verifications

Failed verifications are written to log/recaptcha.log when Tracy is installed. To handle them yourself:

$verifier->onFailure[] = function (ReCaptcha\Response $response, Deimon\ReCaptcha\Version $version, Nette\Http\IRequest $request): void {
	// $response->getErrorCodes(), $response->getScore(), $response->getAction() …
};

$form['captcha']->getResponse() gives you Google's answer for a submitted form.

Development

composer qa                 # PHPStan (level max) + Nette Tester

# browser tests of assets/recaptcha.js (Chrome + Node.js)
cd tests/browser
npm install
php -S 127.0.0.1:8765 server.php &
npm test

License

MIT