exploit3r/kirby-uniform-recaptcha

Kirby 3 reCAPTCHA 保护插件

1.0.2 2021-05-09 23:10 UTC

This package is auto-updated.

Last update: 2024-09-22 19:08:38 UTC


README

A Kirby 3 & 4 插件,实现了 Google reCAPTCHA v3 保护 Uniform 插件。

安装

下载

  • 下载 仓库
  • 将内容解压到 site/plugins/uniform-recaptcha

Git 子模块

将插件作为 Git 子模块添加

git submodule add https://github.com/eXpl0it3r/kirby-uniform-recaptcha.git site/plugins/uniform-recaptcha

Composer

将插件添加到您的仓库

composer require expl0it3r/kirby-uniform-recaptcha

配置

在您的 config.php 文件中设置配置

return [
  'expl0it3r.uniform-recaptcha.siteKey' => 'my-site-key',
  'expl0it3r.uniform-recaptcha.secretKey' => 'my-secret-key',
  'expl0it3r.uniform-recaptcha.acceptableScore' => 0.5
];
  • siteKey & secretKey 可以在 reCAPTCHA 管理页面 上找到
  • acceptableScore 是接受表单提交所需的最小分数,范围在 0.01.0 之间(默认 0.5),请参阅 reCAPTCHA 文档

用法

模板

reCAPTCHA v3 要求通过 JavaScript 提交表单。您可以使用提供的辅助函数,该函数创建一个 JavaScript 回调函数和一个 HTML <button>

<?= recaptchaButton('Submit', 'btn', 'ContactForm') ?>

参数顺序如下

  • 按钮上的文本
  • 额外的 CSS 类
  • 表单的 ID

如果您想要完全控制,可以编写如下内容

<script>
  function onRecaptchaFormSubmit(token) {
    document.getElementById("ContactForm").submit();
  }
</script>
<button class="g-recaptcha btn"
        data-sitekey="<?= option('expl0it3r.uniform-recaptcha.siteKey') ?>"
        data-callback="onRecaptchaFormSubmit"
        data-action="UniformAction">Submit</button>

注意: data-action 是关键的,因为它将在后端进行验证。

为了使 reCAPTCHA 工作正常,您需要提供 Google 的 reCAPTCHA JavaScript 文件。

您可以选择自行包含 脚本 或在模板中使用辅助函数 recaptchaScript()

示例

<form action="<?= $page->url() ?>" method="post" id="ContactForm">
    <label for="name" class="required">Name</label>
    <input<?php if ($form->error('name')): ?> class="erroneous"<?php endif; ?> name="name" type="text" value="<?= $form->old('name') ?>">

    <!-- ... -->

    <?= csrf_field() ?>
    <?= recaptchaButton('Submit', 'btn', 'ContactForm') ?>
</form>
<?= recaptchaScript() ?>

控制器

在您的控制器中,您可以使用 魔法方法 recaptchaGuard() 启用 reCAPTCHA 保护

$form = new Form(/* ... */);

if ($kirby->request()->is('POST'))
{
    $form->recaptchaGuard()
         ->emailAction(/* ... */);
}

致谢

  • 感谢 Johannes Pichler 为 Kirby 2 插件 做出的贡献!
  • 向整个 Kirby 团队表示衷心的感谢!❤