Recaptcha google on angular 6 implementation

旧巷老猫 提交于 2019-12-04 14:15:52

Below implementation gives more in detail and to verify the captcha response is the success on the server side.

In a template-driven form, add a reference to your recaptcha element.

 <recaptcha
            [(ngModel)]="myRecaptcha"
              name="myRecaptcha"
              #recaptcha
              (scriptLoad)="onScriptLoad()"
              (scriptError)="onScriptError()"></recaptcha> 

Now pass the recaptcha ref to your form. In my case. It look like below.

<form class="login-form mt-lg" role="form" (ngSubmit)="onForgot(recaptcha)" #loginForm="ngForm">

  <recaptcha
              [(ngModel)]="myRecaptcha"
              name="myRecaptcha"
              #recaptcha
              (scriptLoad)="onScriptLoad()"
              (scriptError)="onScriptError()"></recaptcha> 
</form>

In forgot.component.ts

export class ForgotComponent implements OnInit {
   onForgot(recaptcha: any) {

        console.log(recaptcha.recaptchaAPI.getResponse());

   }
}

The getResponse() will return a token, which can be verified if the form is submitted from your site as below.

POST: https://www.google.com/recaptcha/api/siteverify

form-data 
secret: YOUR-RECAPTCHA-SECRET
response: above_received_token
remoteip: (optional)

The above call will return the status if the request is actually made from your site and by a user.

{
   "success": true,
   "challenge_ts": "2018-08-15T02:47:46Z",
   "hostname": "localhost"
}

Hope it is useful.

Step3 explains using Reactive Form and Template Driven Form.

In Reactive Form (inside component)

myRecaptcha = new FormControl(false);

onScriptLoad() {
   console.log('Google reCAPTCHA loaded and is ready for use!')
}

onScriptError() {
    console.log('Something went long when loading the Google reCAPTCHA')
}

In Template:

You can add this code

<recaptcha
   [formControl]="myRecaptcha"
   (scriptLoad)="onScriptLoad()"
   (scriptError)="onScriptError()"
></recaptcha>

Same is applicable for Template Driven Form.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!