npm install --save --force ng-hcaptcha
Además crearemos el siguiente servicio para comunicarse con la api de Python. ng generate service service/hcaptcha
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class HcaptchaService {
public isBrowser = false;
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
if (isPlatformBrowser(platformId)) {
this.isBrowser = true;
}
}
getToken(token: string): string {
if (this.isBrowser == true){
const xhr = new XMLHttpRequest();
xhr.open('POST', 'urldestino' + token, false);
xhr.send();
const aux = JSON.parse(xhr.responseText);
return xhr.responseText ;
} else {
return 'false'
}
}
}
Importamos el módulo a nuestra app con el siguiente código:
import {NgHcaptchaModule} from 'ng-hcaptcha';
@NgModule({
declarations: [],
imports: [
NgHcaptchaModule.forRoot({
//modificar con tu llave
siteKey: '10000000-ffff-ffff-ffff-000000000001',
languageCode: 'es' // optional, will default to browser language
})
],
providers: [
]
})
Y añadiremos la funcionalidad en el componente.html: <div *ngIf="robot == true">
<p>Eres un robot</p>
</div>
<div *ngIf="robot == false">
<p>No eres un robot</p>
</div>
<div *ngIf="expirado == true">
<p>Captcha expirado. Recarga la página</p>
</div>
<ng-hcaptcha (verify)="onVerify($event)"
(expired)="onExpired($event)"
(error)="onError($event)">
</ng-hcaptcha>
Y en el componente.ts: public robot: boolean;
public expirado: boolean;
constructor(public captchaSerice: HcaptchaService) {
this.robot = true;
this.expirado = false;
}
onVerify(token: string) {
const auxiliar = this.captchaSerice.getToken(token)
if (auxiliar.includes('true')) {
this.robot = false;
}
}
onExpired(response: any) {
alert('Se ha expirado el tiempo para rellenar el sistema de seguridad. Recarga la página.');
this.expirado=true;
}
onError(error: any) {
alert('Tenemos un probelma, creemos que eres un robot.');
this.robot = true;
// An error occured during the verification process.
}
'''
Función destinada a realizar una verificación de hCaptcha
'''
class Verificar_HCaptcha(Resource):
def post(self, token):
recaptcha_url = 'https://hcaptcha.com/siteverify'
#modificar por vuestra clave
recaptcha_secret_key = '0x0000000000000000000000000000000000000000'
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_HCaptcha, '/verificarh/<string:token>/'),
]
Para terminar, en la web https://dashboard.hcaptcha.com/overview puedes consultar una vista como la siguiente imagen dónde puedes comprobar la cantidad de ingresos que has obtenido ¿Eres un robot?. Según recaptcha de hCaptcha:
Eres un robot, resuelve el Captcha
ng add @nguniversal/express-engine
Si os da un error tipo ERESOLVE unable to resolve dependency tree No os preocupéis, toca jugar entre este comandonpm install --force @nguniversal/express-engine
Y posteriormenteng add @nguniversal/express-engine
Estos dos últimos pasos los tenéis que aplicar tantas cómo sea necesario hasta que no aparezca un error. Primero os comparto el código del component.ts dónde se añade el código necesario para interpretar si se reproduce en la parte del servidor o del navegador.constructor(
public captchaSerice: RecaptchaService, @Inject(PLATFORM_ID) private platformId,
private _changeDetectorRef: ChangeDetectorRef) {
this.isBrowser = isPlatformBrowser(platformId)
this.robot = true;
this.expirado = false;
}
onVerify(token: string) {
const auxiliar = this.captchaSerice.getTokenH(token)
if ( auxiliar.includes('true') ) {
this.robot = false;
};
// The verification process was successful.
// You can verify the token on your server now.
}
onExpired(response: any) {
this.expirado = true;
this.robot = true;
// The verification expired.
}
onError(error: any) {
this.robot = true;
// An error occured during the verification process.
}
Puede ser que os aparezca un error en la linea 2 @Inject(PLATFORM_ID) private platformId tal que así: TS7006: Parameter 'platformId' implicitly has an 'any' type. En ese caso, añadid al fichero tsconfig.json la siguiente línea /* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compilerOptions": {
[...]
"noImplicitAny": false,
}
}
Y ahora se añade el código necesario en la vista (component.html) para evitar el problema del renderizado en el servidor. <div *ngIf="robot == true">
<p>Eres un robot</p>
</div>
<div *ngIf="robot == false">
<p>No eres un robot</p>
</div>
<div *ngIf="expirado == true">
<p>Captcha expirado. Recarga la página</p>
</div>
<div *ngIf="isBrowser">
<ng-hcaptcha (verify)="onVerify($event)"
(expired)="onExpired($event)"
(error)="onError($event)">
</ng-hcaptcha>
</div>