定制 jub/craft-google-recaptcha 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jub/craft-google-recaptcha

Composer 安装命令:

composer require jub/craft-google-recaptcha

包简介

Google reCAPTCHA for Craft CMS

README 文档

README

Stable Version Total Downloads Tests status

Google reCAPTCHA for Craft CMS enables to render and validate the reCAPTCHA widget. It is compatible with both API v2 and v3, including checkbox badge and invisible flavors.

Requirements

This plugin requires Craft CMS 4 or 5 and PHP 8.0.2 or later.

To use the plugin, you will need to get an API site key and secret key which you can configure here.

Installation

  1. Install with composer via composer require jub/craft-google-recaptcha from your project directory or from the Plugin Store section of the Control Panel.
  2. Install the plugin in the Craft Control Panel under Settings → Plugins, or from the command line via ./craft plugin/install google-recaptcha.

Configuration

Control Panel

You can manage configuration setting through the Control Panel by going to Settings → Google reCAPTCHA

  • Provide the Site Key and the Secret Key obtained from your reCAPTCHA account.
  • Select the API version accordingly to the reCAPTCHA type you created the keys upon.
  • For v2 API, select the following parameters:
    • Size: Select the size of the reCAPTCHA widget.
    • Theme: Select the color theme of the reCAPTCHA widget.
    • Badge: Select the position of the reCAPTCHA badge.
  • For v3 API:
    • Default Action: the default action name to be used during reCAPTCHA verification. Defaults to homepage if blank.
    • Default Score Threshold : Minimum score between 0 and 1 to obtain in order for the end user to validate the reCAPTHCHA challenge (see here for help on interpreting the score) . Leave blank for no score checking.
    • Actions: A score threshold can be defined per action here.

Configuration file

You can create a google-recaptcha.php file in the config folder of your project and provide the settings as follow:

return [
    "version"   		=> 2, // Either 2 our 3
    "siteKey"   		=> '', // Site key
    "secretKey" 		=> '', // Secret key
    "size"      		=> 'normal', // (v2) normal, compact or invisible
    "theme"     		=> 'light', // (v2) light or dark
    "badge"     		=> 'bottomright', // (v2) bottomright, bottomleft or inline
    "actionName"        => 'homepage', // (v3) Default action name
    "scoreThreshold"	=> 0.5 // (v3) Value between 0 and 1 to determine the minimum score to validate
    "actions"			=> [ // (v3) List of actions with their associated score threshold value (see the template part below to know how to specify the action parameter in the render method)
    	[
    		'name' 				=> 'some_action_name',
    		'scoreThreshold' 	=> 0.5
    	]
    ]
    
];

⚠️ Any value provided in that file will override the settings from the Control Panel.

Using Google reCAPTCHA

Display Google reCAPTCHA widget in template

You can integrate the Google reCAPTCHA widget in your Twig templates as follow:

{{ craft.googleRecaptcha.render() }}

The render method accept an optional parameter in which you can provide any HTML attributes to apply to the widget container (div for v2, hidden input for v3).
For example, to provide a container id, you can do:

{{ craft.googleRecaptcha.render({id: 'recaptcha-widget'}) }}

💡 For v2 API, you can provide a second boolean argument to the render method to trigger the instant rendering of the widget (ie. {{ craft.googleRecaptcha.render({ id: 'recaptcha-widget' }, true) }}). This is useful if you are working with views loaded through Ajax or Sprig calls and you need to refresh the widget.

v3 special options

Action

An action property can be provided as follow:

{{ craft.googleRecaptcha.render({id: 'recaptcha-widget', action: 'some_action_name'}) }}

In that case, the score threshold to be used for that action can be defined in the "Actions Settings" part of the plugin control panel.

Form ID

To prevent the widget from expiring after 2 minutes, you should provide a formId option to specify the ID of the protected form:

{{ craft.googleRecaptcha.render({id: 'recaptcha-widget', formId: 'some-form-id'}) }}

In that case, reCAPTCHA will be executed upon submit event of the form.

Setting scripts extra attributes

In the first render parameter, scriptOptions special property can be used to add extra attributes to the generated scripts tags.

For example, to support Content Security Policy (CSP), assuming you are using the Sherlock security plugin, you could do the following:

{% set nonce = craft.sherlock.getNonce() %}
{{ craft.googleRecaptcha.render({scriptOptions: {'nonce': nonce}}) }}

Custom reCAPTCHA Widget

If the default widget generation using the Twig command craft.googleRecaptcha.render does not meet your needs, you can generate your own using the plugin settings:

  • Get the API Version (ie 2 or 3): {{ craft.googleRecaptcha.version }}
  • Get the Site Key (parsed value): {{ craft.googleRecaptcha.siteKey }}

💡 If you need even more detailed configuration, you can still access every plugin settings by using {{ craft.app.plugins.plugin('google-recaptcha').settings }}

Verify users submissions

To validate a user submission on server side, you can use the built-in method:

GoogleRecaptcha::$plugin->recaptcha->verify();

For example, in a module controller, you could do something like this:

public function actionSubmitForm() {
	if(GoogleRecaptcha::$plugin->recaptcha->verify()) {
		// Do something useful here
	}
	else {
		Craft::$app->session->setError('Looks like you are a robot!');
	}

}

Verify Guest Entries submissions

In order to add a reCAPTCHA verification when working with Craft Guest Entries plugin, you can do something like the following in a project module:

Event::on(SaveController::class, SaveController::EVENT_BEFORE_SAVE_ENTRY, function (SaveEvent $e) {
    /** @var Entry $submission */
    $submission = $e->entry;
    $submission->setScenario(Element::SCENARIO_LIVE);
    $submission->validate();
    // Check reCAPTCHA
    $isValid = GoogleRecaptcha::$plugin->recaptcha->verify();
    if (!$isValid) {
        $submission->addError('recaptcha', 'Please, prove you’re not a robot.');
        $e->isValid = false;
    }
});

Verify Contact Form submissions

In order to add a reCAPTCHA verification when working with Contact Form, you can do something like the following in a project module:

Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e) {
    /** @var Submission $submission */
    $submission = $e->sender;
    // Check reCAPTCHA
    $isValid = GoogleRecaptcha::$plugin->recaptcha->verify();
    if (!$isValid) {
        $submission->addError('recaptcha', 'Please, prove you’re not a robot.');
    }
});

Available events

  • The \juban\googlerecaptcha\events\BeforeRecaptchaVerifyEvent event is triggered just before a reCAPTCHA verification is performed. You can use that event to:
    • Bypass the verification by setting the skipVerification event property to true. In that case, verification will be considered as successful.
    • Cancel the verification by setting the isValid event property to false. In that case, verification will be considered as failed.

jub/craft-google-recaptcha 适用场景与选型建议

jub/craft-google-recaptcha 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11.13k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2022 年 07 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cms」 「Craft」 「craftcms」 「Google ReCaptcha」 「craft-plugin」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jub/craft-google-recaptcha 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jub/craft-google-recaptcha 我们能提供哪些服务?
定制开发 / 二次开发

基于 jub/craft-google-recaptcha 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 11.13k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-24