How to set up reCAPTCHA v3 (Tutorial)

What is reCAPTCHA?

reCAPTCHA is a free service from Google that helps protect websites from spam and abuse. A “CAPTCHA” is a turing test to tell human and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. By adding reCAPTCHA to a site, you can block automated software while helping your welcome users to enter with ease.

Step 1 - Register and Pre-Setup


Alright so Adding This little thing to your site is now Really simple with reCAPTCHA v3 however i Must stress it is still in BETA. So anything may change at any time and for all i know this little tutorial will be depreciated in 20 minutes ¯_(ツ)_/¯

First you must apply and get your Site and Secret keys HERE
For this i will be using my music site bombandkou.com as the example.

Now for this we are going to be using it inside of an HTML Component and those iframes have their own url for the code. so www.bombandkou.com becomes www-bombandkou-com.filesusr.com
Set your Label and add the domains, Accept to the terms of service. I know no one reads those but its always a good idea to just skim it.

Ok so now we have our Keys and some Code, and various info and calls that are important to us


Now that that is set up its time to add it to the site. add an iFrame Html component to your site and add the following code inside, replacing SITE_KEY for your site key

You might want to do this in Notepad++/Notepad before putting it in the component as working with code in that is Horrendous. (Wix staff please update that? k thanks!)

<script src="https://www.google.com/recaptcha/api.js?render=SITE_KEY"></script>
  <script>
  //this will run as soon as the html component loads you could alternatively have this code run in an onMessage event for more control if you wish to and i might make how to do this below
  grecaptcha.ready(function() {
      grecaptcha.execute('SITE_KEY', {action: 'formSubmit'}).then(function(token) {
       window.parent.postMessage(token,'*');
      });
  });
  </script>

Now where we see action: we have several cases we can give it


These are just suggestions, you can give it Any case you want. the purpose is all the info is tracked on the google admin panel, if you have multiple pages using reCAPTCHA its a good idea to name them properly.

I recommend putting all this code on a locked/hidden Testing page as you will always get an Error in testing unless you find your Preview Environment URL which is a uuid and looks something like dsfjhkj3-4htk-j238-923f9o3f9823f.htmlcomponentservice.com (hit random keys for this dont actually use it you will get an error still) So testing this in preview mode is difficult.

Step 2 - Site Code


Now we move on to Site Code. We have the reCAPTCHA on the site and all set up but now we have to actually Use the key. First thing. Get the Token provided by the html component. To do that we must create an onMessage event trigger.

Inside the html_message function the Token we just generated is a string in event.dataWe can use this to verify with the api at https://www.google.com/recaptcha/api/siteverify for this we require the Response and the Secret, Now the secret is not something ANYONE can have so we must do this in Backend code.
i created a Web Module in the Backend titled reCAPTCHA.jswthe following is the code i have in my backend simply calls to the api with the token;


// Filename: backend/reCAPTCHA.jsw (web modules need to have a .jsw extension)
import { fetch } from 'wix-fetch';
const secret = "SECRET_KEY" //replace with your Secret from step 1

export function verify(token) {
const url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + token
 return fetch(url, { method: "get" })
        .then((httpResponse) => {
 if (httpResponse.ok) {
 return httpResponse.json();
            }
        })
}

Now we have import this function back on our page with;

import {verify} from 'backend/reCAPTCHA'

Now we have a function that returns a promise with all the info from google.The way our new function is called is like so: (your export_function may be different from mine, Mine is #html6)the following is the call and All info returned.

export function html6_message(event, $w) {
    verify(event.data).then((data)=>{
        let success = data.success // true
        let challenge_ts = data.challenge_ts // "2018-08-27T19:04:58Z" 
        let hostname = data.hostname //for me is www-bombandkou-filesusr.com
        let score = data.score //Higher the better. Most users will get around 0.9
        let action = data.action
    })
}

If you have any questions regarding setting this up or implementing it on your site go ahead and ask. If you have a better way to do things Also let us know below.

2 Likes

A basic implementation of this would be;


(Displays error cause it cant run on the Editor, it displays normally on the site)

import {verify} from 'backend/reCAPTCHA'
var reCaptchaScore = 0.0 // Default Status to Failure
$w.onReady(function () {
 //TODO: write your page related code here...
});
export function html6_message(event, $w) {
    verify(event.data).then((data)=>{
        reCaptchaScore = data.score
    })
}
export function SubmitButton_click(event, $w) {
 if (reCaptchaScore < 0.5) {
        console.log("Probable Bot")
 //Deny Access or give a second test if it is a genuine user
    } else {
 //User has a score higher than 0.5 Submit the data
    }
}

Preferably though the info would be sent and handled in the backend

Example in Practical use: https://www.bombandkou.com/messages

Hi. Thanks for the tutorial. I just can’t seem to get it to work.

I am trying to use on a lightbox that pops up for product reviews. This is the page I am trying to get to work on (when you click add review the lightbox opens)

I have tried dropping in your basic example to test but nothing works, I don’t even see an error.

I have the following page code inserted.

import {verify} from 'backend/reCAPTCHA'
var reCaptchaScore = 0.0 // Default Status to Failure

export function html6_message(event, $w) {
    verify(event.data).then((data)=>{
        reCaptchaScore = data.score
    })
}

export function button2_click(event, $w) {
 if (reCaptchaScore < 0.5) {
        console.log("Probable Bot")
 //Deny Access or give a second test if it is a genuine user
    } else {
 //User has a score higher than 0.5 Submit the data
    }
}

I have set up the back end module. Changed all keys.

I thought it might be due to no domain but tested on another of my sites to no avail.

Any help would be amazing.

Thanks.

helo
your tutorial is great. I succeeded to implement but I want to see how you integrate with a page or wix form but I cannot make it. it is a simple form with a button send. I wanted to look at your link https://www.bombandkou.com/messages but it is not available anymore. Is it possible to communicate the correct link or give some more info about integration with a form?

Awesome guide, thanks a lot!