在 WordPress 登录屏幕中实施 reCAPTCHA v3

implement reCAPTCHA v3 in WordPress loginscreen

Google 刚刚发布了他们的 recaptcha 的新测试版:reCaptcha v3。 我正在尝试在我的 WordPress 登录屏幕中实现这一点。但是它确实在右下角显示了 recaptcha 徽标(如此处:https://www.google.com/recaptcha/intro/v3beta.html),这表明脚本已加载我似乎无法触发它。

我做了什么:

1) 在我的登录屏幕的 header 中加入了 API 脚本(有效)

2) 排队一些 js 来触发验证码

排队

public static function load_login_scripts()
{
    wp_enqueue_script( 'recaptchav3', 'https://www.google.com/recaptcha/api.js?render=KEY');
    wp_enqueue_script( 'custom-recaptcha', 'somepath/recaptcha.js' );
}



add_action( 'login_enqueue_scripts', array($this, 'load_login_scripts'));

js触发验证码

document.addEventListener("DOMContentLoaded", function(event) { 
    grecaptcha.ready(function() {
        grecaptcha.execute('MYKEY', {action: 'login'}).then(function(token) {
            console.log(token);
        });
    });
});

这确实在控制台中记录了一个(356 个字符长)令牌。

很高兴知道

谁能告诉我我错过了什么?

这是可行的解决方案,请将 'functions.php' 中的函数更改为此。

function load_login_scripts()
{
    wp_enqueue_script( 'recaptchav3', 'https://www.google.com/recaptcha/api.js?render=KEY');
    wp_enqueue_script( 'custom-recaptcha', '/somepath/recaptcha.js' );
}

add_action( 'login_enqueue_scripts', 'load_login_scripts');

首先,确保启用JavaScript。如果没有,请参阅 reCaptcha faq 中的 link。

我已经测试了以下代码,没有任何错误,并且在右下角有 reCaptcha Logo:

reCaptchaV3/reCaptchaV3.php

<?php 
/*
 * Plugin Name: reCaptchaV3 Beta
 * Plugin Author: N/A
 * Version: 0.1
 */

final class reCaptchaV3
{

    public function __construct()  { }

    public function init()
    {
        add_action( 'login_enqueue_scripts', array($this, 'load_login_scripts') );
    }

    public static function load_login_scripts()
    {
        wp_enqueue_script( 'recaptchav3', 'https://www.google.com/recaptcha/api.js?render=SITE_KEY');
        wp_enqueue_script( 'custom-recaptcha', plugin_dir_url( __FILE__ ) . 'recaptcha.js' );
    }
}

add_action( 'init', array( new reCaptchaV3(), 'init' ) );

reCaptchaV3/recaptcha.js

document.addEventListener("DOMContentLoaded", function(event) { 
    grecaptcha.ready(function() {
        grecaptcha.execute('SITE_KEY', {action: 

            'login'}).then(function(token) {
                console.log(token);
            });
    });
});  

版本问题

login_enqueue_scripts 可用 after WordPress version 3.1.0 所以确保之后使用 WordPress 版本。


API 键

here, not sure if they work for reCaptcha v3 Beta but I had my registered at admin console 获取测试密钥。尽管 localhost 不是受支持的域,因此如果您在本地工作,请使用虚拟主机。

如果您在 admin console 中添加或更改了域,更改需要 30 分钟才能生效

测试键:

站点密钥:6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
密钥:6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe


辅助功能

如果您没有看到 reCaptcha 徽标,可能 google.com 无法访问脚本加载。尝试将其替换为 recaptcha.net,如下所示:

wp_enqueue_script( 'recaptchav3', 'https://www.recaptcha.net/recaptcha/api.js?render=SITE_KEY');

如果您在网站上使用内容安全策略 (CSP),请查看 reCaptcha faq