How To Implement reCaptcha In Angular.

In this article we are going to learn how to implement reCaptcha v2 in angular.

 

Step1: Create new Application

ng new recapcha-angular

 

Step2: Install node-modules

yarn

 

Step3: install ReCaptcha

yarn add ng-recaptcha

 

Step4: In app.modules.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RecaptchaModule } from 'ng-recaptcha';

@NgModule({
  declarations: [
    AppComponent,
   
  ],
  imports: [
    BrowserModule,
    RecaptchaModule,
    AppRoutingModule,
    FormsModule,ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Step5: in app.component.ts

import { Component ,ElementRef,ViewChild,Inject,VERSION} from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RecaptchaComponent,RecaptchaErrorParameters } from 'ng-recaptcha';

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

export class AppComponent {
  version = VERSION.full;
  lang = 'en';
  FormGroup: FormGroup|any;
  @ViewChild('captchaElem') captchaElem: RecaptchaComponent | any;
  @ViewChild('langInput') langInput: ElementRef|any;
  recComp: RecaptchaComponent|any;
  

  constructor(private formBuilder: FormBuilder){}

    ngOnInit() {
      this.FormGroup = this.formBuilder.group({
        recaptcha: ['', Validators.required]
      });
    }

    public getToken(captchaResponse: string): void {
      console.log(`Resolved captcha with response:' captchaResponse);
    }
  
    public onError(errorDetails: RecaptchaErrorParameters): void {
      console.log(`Recaptcha error encountered; details:`, errorDetails);
    } 
}

 

Step6: in app.component.html

<re-captcha
  (resolved)="getToken($event)"
  (error)="onError($event)"
  errorMode="handled"
  siteKey="<siteKey>"></re-captcha>

 

Step7: Generate Your secret key on this link

https://www.google.com/recaptcha/admin/create

 

Step8: Now Run Your project and check Your Output

 

your project output look like this.

 

Step9: Now you need to verify that google token is valid or not by below API.

https://www.google.com/recaptcha/api/siteverify?secret=%7B0%7D&response=%7B1%7D



In, secret- write your secret key,

Response - write your token

 

Step10:Your Output Look like this

Submit a Comment

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

Subscribe

Select Categories