radiergummi / recaptcha-verify
使用谷歌API验证Recaptcha
Requires
- craftcms/cms: ^3.0.0-RC1
- google/recaptcha: ^1.1
README
使用谷歌API验证Recaptcha。
要求
此插件需要Craft CMS 3.0.0-beta.23或更高版本。
安装
要安装插件,请按照以下说明操作。
- 打开您的终端并转到您的Craft项目
cd /path/to/project
- 然后告诉Composer加载插件
composer require radiergummi/recaptcha-verify
- 在控制面板中,转到 设置 → 插件,然后点击Recaptcha Verify的 “安装” 按钮。
Recaptcha Verify概述
Recaptcha Verify通过谷歌库验证Recaptcha令牌。这可能是我为任何CMS编写的最小型插件(忽略我为WordPress编写的debugTheme
插件,它有惊人的3行)。
使用Recaptcha Verify
Recaptcha Verify为Craft提供了一个新的POST
操作:recaptcha-verify/verify
,您可以使用它来验证您的响应。它还提供了对联系表单插件的监听器,因此您可以验证您的提交。详细信息请见下面。
该操作期望正文内容包含CRAFT_CSRF_TOKEN
和token
,其中token是从谷歌收到的Recaptcha令牌。要设置客户端验证过程,请查阅谷歌文档。
如果以下情况发生,响应将是一个400错误:
- 您在设置中没有配置密钥
- POST体中没有令牌
如果以下情况发生,响应将是一个200成功:
- 令牌可以验证(
{status: 'success'}
作为响应体) - 令牌不能被验证(
{status: 'failed'}
作为响应体)
听起来可能很奇怪,不会为验证问题抛出错误,但实际上这正是所请求的操作的结果。您如何在客户端处理该错误取决于您。 如果对此有实质性的兴趣,将其更改为抛出错误,我将更新插件。
配置Recaptcha Verify
有两个设置字段:您的Recaptcha API 站点密钥和密钥。您可以从这里获取它们: https://www.google.com/recaptcha/admin
填写Google说明页面上显示的值。您还可以使用名为recaptcha-verify.php
的(多环境感知)配置文件。
联系表单集成
这仍然是计划在0.3.0中完成的TODO
😊
目前我还不确定如何使其可选,如果有人想帮忙,我愿意接受PR或问题。
要在表单提交中验证令牌,请在您的表单提交中包含字段message[token]
。Recaptcha目前不支持(并且可能永远都不会支持)没有JavaScript的浏览器,因此您无论如何都需要通过JS提交。
以下是一个示例表单供您参考
<!-- Create your form. I skipped all the fields you'll likely want to include for simplicity --> <form action="/" method="POST" id="contact-form"> <input type="submit" value="Send"> </form> <!-- Provide a container to render the recaptcha in --> <div id="recaptcha-container"></div> <!-- Include the Recaptcha script, passing our callback --> <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer> <script> // this will hold our token let recaptchaToken = null; // callback for Recaptcha. We passed that as a parameter to `onload` in the script URL const onloadCallback = function() { // render the widget in our container grecaptcha.render('recaptcha-container', { sitekey: 'your_site_key', // that one is passed in the settings callback: verifyCallback, // our verification callback below theme: 'dark' // optional theme }); }; // set recaptchaToken to the response from Google const verifyCallback = function(response) { recaptchaToken = response; }; // capture the submit event from our form document.querySelector('#contact-form').addEventListener('submit', event => { // prevent it from automatically submitting just yet event.preventDefault(); // if we don't have a token at this point, the user did not confirm the Recaptcha yet if (!recaptchaToken) { return alert('Please confirm the Recaptcha first!'); } // using Axios here for less complex code, you're free to use whatever AJAX library of course. // we pass the token (among our other fields, of course) as a parameter axios.post('/', { action: 'contact-form/send' 'message[token]': recaptchaToken }); }); </script>
由 Radiergummi 提供