欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hcaptcha使用方法

程序员文章站 2022-06-21 12:30:22
...

方法一,直接显示,回调返回验证值

<script src='https://www.hCaptcha.com/1/api.js' async></script>
<div id="h-captcha" data-callback="captchaCallback" data-sitekey="key" class="mt-4 h-captcha"></div>

方法二,用js创建

<script src="https://js.hcaptcha.com/1/api.js?onload=hcaptchas&render=explicit" async defer></script>
<script>
    var hcaptchas = function () {
    	//获取id
        var widgetID = hcaptcha.render('h-captcha', { sitekey: 'key' })
        //异步反馈是否成功
        hcaptcha.execute(widgetID, { async: true })
            .then(({ response, key }) => {
                //success
                $.ajax({
                    url: '/hcaptcha',
                    type: 'post',
                    data: {response: response},
                    beforeSend: function(){
                        loading();
                    },
                    success: function (e) {
                        console.log(e)
                        if (e.error_code == 0) {
                            toast(e.msg);
                            //window.location.href="/";
                        } else {
                            toast(e.msg, {type: 'danger'})
                        }
                    },
                    complete: function () {
                        loading(false);
                    }
                })
            })
            .catch(err => {
                toast('fail', {type: 'danger'});
            });
    };

    function captchaCallback (e) {
        if (e){
            $.ajax({
                url: '/hcaptcha',
                type: 'post',
                data: {response: e},
                beforeSend: function(){
                    loading();
                },
                success: function (e) {
                    console.log(e)
                    if (e.error_code === 0) {
                        toast(e.msg);
                        window.location.href = referrer();
                    } else {
                        toast(e.msg, {type: 'danger'})
                    }
                },
                complete: function () {
                    loading(false);
                }
            })
        }
    }
</script>