npm i ng-recaptcha --force
Además crearemos el siguiente servicio para comunicarse con la api de Python. ng generate service service/recaptcha
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import { Observable, throwError} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {catchError, map} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class RecaptchaService {
constructor(private http: HttpClient) {
}
/*
Modo de comunicación con el servidor asíncrono
parametro token: string
return Observable<any>
*/
getTokenClientModule(token: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
return this.http.post<any>( 'http://0.0.0.0:5000/api/v1/verificar/' + token +'/', httpOptions)
.pipe(
map((response) => response),
catchError((err) => {
console.log('error caught in service')
console.error(err);
return throwError(err);
})
);
}
}
Importamos el módulo a nuestra app con el siguiente código:
import {RECAPTCHA_V3_SITE_KEY, RecaptchaV3Module} from 'ng-recaptcha';
@NgModule({
declarations: [],
imports: [
RecaptchaV3Module,
HttpClientModule
],
providers: [
{
provide: RECAPTCHA_V3_SITE_KEY,
useValue: 'pon_la_key_de_google',
}]
})
Y añadiremos la funcionalidad en el componente: <div class="container">
<div class="row">
<div *ngIf="robot == true">
<p >Ejemplo de ejecución HttpClient(asincrona) de google recaptcha
</p><button (click)="getInfoRecaptcha()" class="btn btn-primary">
Comprobación</button>
</div>
</div>
</div>
<div *ngIf="presionado == true">
<p>Cargando ...</p>
</div>
<div *ngIf="robot == true">
<p>De momento eres un robot, presiona el botón</p>
</div>
<div *ngIf="robot == false">
<p>No eres un robot, Enhorabuena </p>
</div>
public robot: boolean;
public presionado: boolean;
constructor( private httpService: RecaptchaService, private recaptchaV3Service: ReCaptchaV3Service) {
this.robot = true;
this.presionado = false;
}
ngOnInit(): void {
this.robot = true;
this.presionado = false;
}
getInfoRecaptcha() {
this.robot = true;
this.presionado = true;
this.recaptchaV3Service.execute('')
.subscribe((token) => {
const auxiliar = this.httpService.getTokenClientModule(token)
auxiliar.subscribe( {
complete: () => {
this.presionado = false;
},
error: () => {
this.presionado = false;
this.robot = true;
alert('Tenemos un problema, recarga la página página para solucionarlo o contacta con 1938web@gmail.com');
},
next: (resultado: Boolean) => {
if (resultado === true) {
this.presionado = false;
this.robot = false;
} else {
alert('Error en el captcha. Eres un robot')
this.presionado = false;
this.robot = true;
}
}
});
}
);
}
class Verificar_Captcha(Resource):
def post(self, token):
recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
recaptcha_secret_key = ''
payload = {
'secret': recaptcha_secret_key,
'response': token,
'remoteip': request.remote_addr,
}
response = requests.post(recaptcha_url, data=payload)
result = response.json()
return result.get('success', False)
local_resources = [
(Verificar_Captcha, '/verificar/<string:token>/'),
]
Para terminar, en la web https://www.google.com/u/3/recaptcha/admin/ puedes consultar una vista como la siguiente imagen dónde puedes comprobar la cantidad de gente que ha realizado el login y la puntuación obtenida de media. Ejemplo de ejecución HttpClient(asíncrona) de google recaptcha
¿Eres un robot?. Según recaptcha de Google de momento eres un:
Eres un robot
npm i ng-recaptcha --force
Además crearemos el siguiente servicio para comunicarse con la api de Python. ng generate service service/recaptcha
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class RecaptchaService {
constructor() {
}
/*
Modo de comunicación con el servidor síncrono
parametro token: string
return string
*/
getToken(token: string): string {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'urldestino' + token, false);
xhr.send();
return xhr.responseText ;
}
}
Importamos el módulo a nuestra app con el siguiente código:
import {RECAPTCHA_V3_SITE_KEY, RecaptchaV3Module} from 'ng-recaptcha';
@NgModule({
declarations: [],
imports: [
RecaptchaV3Module
],
providers: [
{
provide: RECAPTCHA_V3_SITE_KEY,
useValue: 'pon_la_key_de_google',
}]
})
Y añadiremos la funcionalidad en el componente:
<h1>Ejecución XmlHttpRequest</h1>
<div class="container">
<div *ngIf="robot == true">
<p class="fw-light lead mb-4">Ejemplo de ejecución XmlHttpRequest (sincrona) de google recaptcha
</p><button (click)="getInfoRecaptcha()" class="btn btn-primary">
Comprobación</button>
</div>
</div>
<div *ngIf="robot == true">
<p>De momento eres un robot, presiona el botón</p>
</div>
<div *ngIf="robot == false">
<p>No eres un robot, Enhorabuena </p>
</div>
public robot: boolean;
public presionado: boolean;
constructor( private recaptchaV3Service: ReCaptchaV3Service, public captchaSerice: RecaptchaService
) {
this.robot = true;
this.presionado = false;
}
ngOnInit(): void {
}
getInfoRecaptcha() {
this.robot = true;
this.presionado = true;
this.recaptchaV3Service.execute('')
.subscribe((token) => {
const auxiliar = this.captchaSerice.getToken(token)
if ( auxiliar.includes('true') ) {
this.robot = false;
}
});
}
class Verificar_Captcha(Resource):
def post(self, token):
recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
recaptcha_secret_key = ''
payload = {
'secret': recaptcha_secret_key,
'response': token,
'remoteip': request.remote_addr,
}
response = requests.post(recaptcha_url, data=payload)
result = response.json()
return result.get('success', False)
local_resources = [
(Verificar_Captcha, '/verificar/<string:token>/'),
]
Para terminar, en la web https://www.google.com/u/3/recaptcha/admin/ puedes consultar una vista como la siguiente imagen dónde puedes comprobar la cantidad de gente que ha realizado el login y la puntuación obtenida de media. Ejemplo de ejecución XmlHttpRequest(síncrona) de google recaptcha
¿Eres un robot?. Según recaptcha de Google:
Eres un robot