VictorPrdh / reCaptchaBundle
使用Google reCAPTCHA v2/v3作为表单类型,适用于Symfony 5.4+
1.9.0
2024-04-28 08:51 UTC
Requires
- php: >=7.2.5
- google/recaptcha: ^1.2
- symfony/form: ^5.4|^6.0|^7.0
- symfony/framework-bundle: ^5.4|^6.0|^7.0
- symfony/translation: ^5.4|^6.0|^7.0
- symfony/twig-pack: ^1.0
- symfony/validator: ^5.4|^6.0|^7.0
README
使用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) }}
贡献
欢迎提交拉取请求。对于重大更改,请首先提交一个问题来讨论您想进行哪些更改。
如果您说一种没有翻译的语言,您的帮助受到欢迎。