Sharing reCAPTCHA API keys and tokens

Posts in the developer's cookbook category describe topics that require technical knowledge. Be warned and use the techniques at your own risk. Unless you are an experienced developer, you are strongly advised to ask a professional for support.

With Contact Form 7’s reCAPTCHA (v3) integration ability, you can protect your contact forms from spambots. Since a spambot targets everything—not only contact forms—you may also want to protect other components on your website (such as comment forms) using reCAPTCHA technology.

Fortunately, Contact Form 7’s reCAPTCHA integration is designed to be open and accessible to other components. In this recipe, I’ll tell you how you can retrieve reCAPTCHA API keys and tokens from Contact Form 7 and reuse the data within your own reCAPTCHA plugin.

Sharing reCAPTCHA API keys

To retrieve the reCAPTCHA API keys that you set through Contact Form 7’s Integration menu page, run PHP code in your plugin like the following:

$service = WPCF7_RECAPTCHA::get_instance();
$sitekey = $service->get_sitekey();
$secret = $service->get_secret( $sitekey );

Note: you need to know the site key to retrieve the secret key, so retrieve the site key first.

Sharing reCAPTCHA tokens

reCAPTCHA API responds to a grecaptcha.execute() request with a token. By verifying the token, you become informed about the likelihood that the site access is by a human or a spambot.

Since this information is site global, not only about contact forms, the tokens are also useful for other components on the site.

When Contact Form 7 calls grecaptcha.execute() and obtains a token from the API, it triggers a custom DOM event wpcf7grecaptchaexecuted. You can access the token through the event object with a front-end JavaScript code.

For example, Contact Form 7 itself also uses this event to pass a token to a form field in a way like the following:

document.addEventListener( 'wpcf7grecaptchaexecuted', function( event ) {
  var fields = document.querySelectorAll(
    "form.wpcf7-form input[name='g-recaptcha-response']"

  for ( var i = 0; i < fields.length; i++ ) {
    var field = fields[ i ];
    field.setAttribute( 'value', event.detail.token );
} );