VictorPrdh/reCaptchaBundle

使用Google reCAPTCHA v2/v3作为表单类型,适用于Symfony 5.4+

安装次数: 27,883

依赖项: 0

建议者: 0

安全: 0

星标: 10

关注者: 1

分支: 2

开放问题: 2

类型:symfony-bundle

1.9.0 2024-04-28 08:51 UTC

This package is auto-updated.

Last update: 2024-08-28 09:43:16 UTC


README

bundle version

使用symfony轻松实现Google reCAPTCHA。

安装

在开始安装bundle之前,您需要在此处注册reCAPTCHA密钥 这里

使用 Composer 安装此bundle。

composer require victor-prdh/recaptcha-bundle

使用Symfony flex

您可以通过使用symfony/flex快速配置此bundle。

  • 对于 google/recaptcha 回答 no
  • 对于 victor-prdh/recaptcha-bundle 回答 yes

如果一切正常,您应该在配置文件夹的 "bundles.php" 文件中找到此bundle。

//config/bunldes.php
<?php
return [
    ...
    VictorPrdh\RecaptchaBundle\RecaptchaBundle::class => ['all' => true]
];

如果没有看到此行,请添加它。

您可以直接进入 使用部分

不使用Symfony flex

如果您不想或不使用flex配方,您可以在配置文件夹中创建一个 "recaptcha.yaml" 文件 ("config/packages/recaptcha.yaml")。

#config/packages/recaptcha.yaml
recaptcha:
  google_site_key: '%env(GOOGLE_RECAPTCHA_SITE_KEY)%'
  google_secret_key: '%env(GOOGLE_RECAPTCHA_SECRET_KEY)%'

创建此配置文件后,您可以在您的 .env 文件中添加以下内容

###> victor-prdh/recaptcha ###
# https://www.google.com/recaptcha/admin  <--- get keys here
GOOGLE_RECAPTCHA_SITE_KEY='your site key'
GOOGLE_RECAPTCHA_SECRET_KEY='your secret key'
###< victor-prdh/recaptcha ###

现在是更新bundle的时候了,如果您不这样做,bundle将不会使用您的密钥。

composer update victor-prdh/recaptcha-bundle

使用

Symfony表单集成

您现在有一个可用于所有表单的 "ReCaptchaType" 类。您可以在您的FormBuilder中像使用 "TextType""PasswordType" 一样使用它。

<?php

namespace App\Form;

use VictorPrdh\RecaptchaBundle\Form\ReCaptchaType;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add("recaptcha", ReCaptchaType::class);

        // If you want an "invisible" recaptcha protection use this:
        // $builder->add("recaptcha", ReCaptchaType::class, ["type" => "invisible"]);
    }
}

在您的Twig视图中显示错误

创建表单后,您可以使用Symfony像往常一样渲染它。您可以在您的twig文件中这样显示它

{{ form_start(form) }}

    {{ form_row(form.recaptcha) }} 
    {# must be the same name of this put on the FormBuilder #}

    {{ form_errors(form.recaptcha) }}
    {# That will display the error of the captcha to user #}

{{ form_end(form) }}

贡献

欢迎提交拉取请求。对于重大更改,请首先提交一个问题来讨论您想进行哪些更改。

如果您说一种没有翻译的语言,您的帮助受到欢迎。

许可协议

MIT