How to Integrate ReCaptcha in Angular 8

We are going to Integrate ReCaptcha in Angular 8 applications. In this article, we will learn ReCaptcha integration client and server side verification, So let’s get started how to integrate ReCaptcha in Angular 8 application with live demo

Before start Angular 8 ReCaptcha integration. We need a Angular 8 Project. If you don’t know how to create a new angular 8 project. Follow this tutorial.

Create Site Key and Secret Key

To start using reCAPTCHA, you need to sign up for an API key pair for your site. The key pair consists of a site key and secret key. The site key is used to invoke reCAPTCHA service on your site or mobile application. The secret key authorizes communication between your application backend and the reCAPTCHA server to verify the user’s response. The secret key needs to be kept safe for security purposes.

Add a Placeholder

We need to add a placeholder for the ReCaptcha. To add the placeholder, open app.component.html file and put the below html markup

<div class="row mt-5">
  <div class="col-md-9 mx-auto">
      <h2 class="text-left">Angular 8 - Google ReCaptcha demo</h2>
      <div class="card mt-3">
          <div class="card-body">
              <div #recaptcha ></div>
          </div>
      </div>
  </div>
</div>

Basically we need only <div #recapthca></div> but to looks better i have added some styling.

Next, Open the app.component.ts file and add the below code

@ViewChild('recaptcha', {static: true }) recaptchaElement: ElementRef;

Access <div #recaptcha>: recaptchaElement is a reference to <div # recaptcha> inside app.component.html file. ViewChild directive creates a direct link between <div> element and a recaptchaElement member variable.

Load the Google ReCaptcha Library

Next, Open your component.ts file and add the below method. I am going to add this method on the app.component.ts file

addRecaptchaScript() {

  window['grecaptchaCallback'] = () => {

  }

  (function(d, s, id, obj){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://www.google.com/recaptcha/api.js?onload=grecaptchaCallback&amp;render=explicit";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'recaptcha-jssdk', this));

}

This method will load the Google ReCaptcha Library

You may notice that We have created a grecaptchaCallback method. We have added a callback when the Google ReCaptcha Library will loaded.

Next, Call the above method from ngOnInit () method

ngOnInit() {
  this.addRecaptchaScript();
}

Render ReCaptcha

Next, We need to render the ReCaptcha. To render the ReCaptcha add the below method.

renderReCaptcha() {
  window['grecaptcha'].render(this.recaptchaElement.nativeElement, {
    'sitekey' : 'YOUR_SITE_KEY ',
    'callback': (response) => {
        console.log(response);
    }
  });
}

Here, Change the YOUR_SITE_KEY with your site key, Which we have created at the start of this tutorial.

Now, We need to call renderReCaptcha method after the ReCaptcha library loaded. We have to make some changes in the addRecaptchaScript method. We will call the renderReCaptcha method on callback function. After the changes our addRecaptchaScript will look like this

addRecaptchaScript() {

  window['grecaptchaCallback'] = () => {
    this.renderReCaptcha();
  }

  (function(d, s, id, obj){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { obj.renderReCaptcha(); return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://www.google.com/recaptcha/api.js?onload=grecaptchaCallback&amp;render=explicit";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'recaptcha-jssdk', this));

}

After the complete all the above steps, our component will looks like this

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  @ViewChild('recaptcha', {static: true }) recaptchaElement: ElementRef;

  constructor() { }

  ngOnInit() {
    this.addRecaptchaScript();
  }

  renderReCaptch() {
    window['grecaptcha'].render(this.recaptchaElement.nativeElement, {
      'sitekey' : '6LePbq4UAAAAAPqwJU8u5g1Of1TIEMyoPpJQpyaD',
      'callback': (response) => {
          console.log(response);
      }
    });
  }

  addRecaptchaScript() {

    window['grecaptchaCallback'] = () => {
      this.renderReCaptch();
    }

    (function(d, s, id, obj){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) { obj.renderReCaptch(); return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://www.google.com/recaptcha/api.js?onload=grecaptchaCallback&amp;render=explicit";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'recaptcha-jssdk', this));

  }

}

Verifying the user’s response

We have one ReCaptcha integration with Angular 8, Now we need to verify the user’s response. let’s see how to verify a user’s response to a reCAPTCHA challenge from your application’s backend.

After you get the response token, you need to verify it within two minutes with reCAPTCHA using the following API to ensure the token is valid.

API Request

URL: https://www.google.com/recaptcha/api/siteverify
METHOD: POST
POST Parameter:

secretRequired. The shared key between your site and reCAPTCHA.
responseRequired. The user response token provided by the reCAPTCHA client-side integration on your site.
remoteipOptional. The user’s IP address.

Sample Code For Php

<?php

$data = http_build_query(array(
  'secret' => "YOUR_SECRET_KEY",
  'response' => "03AOLTBLReNhdz3sTw46RKhiVHu-eLNtu0BvWybASGv1zT9AKzauZPP36zxmGIaapD3wIu9OkPKT5LcHDSZ_scwPfRaT6u9PlDz0gk_OnK8cema0_cOAsGaw7fcFMTQyj9v32talc9L8McnAVOPcNhP_dDpoNxETtAIXSFZOOegTFNYQPvZx6FfTe_Pv4CwRP08T2Cjq8n8KZyge9RMbUdJOYamo3OhuE-9IQ-G_GWj-04en-x3KTcNH7AWfzHRrEJnNT9uKbb5PY6ywtQlpbZ3YKq5HqvbOd1KMkDKgbUCeI5cK0pM3DWLDgBD2mdRGA28IukWSmy_Unn"
));

$curl = curl_init();
  
$captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";

curl_setopt($curl, CURLOPT_URL,$captcha_verify_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);


$captcha_output = curl_exec ($curl);
curl_close ($curl);
$decoded_captcha = json_decode($captcha_output);

print_r($captcha_output);


Here, You need to change the YOUR_SECRET_KEY with your secret key

Running application:

Run the application using ng serve --o

Preview

3 Comments

  1. John said:

    Great!! This is what I was looking for

    August 2, 2019
    Reply
  2. santosh raju said:

    is this will notify when ever recaptcha got expired?

    September 17, 2019
    Reply
  3. Lars said:

    Awesome! Thank you so much

    October 21, 2019
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *