@@ -62,7 +62,12 @@ karser_recaptcha3:
62
62
63
63
Usage
64
64
-----
65
- ` ` `
65
+
66
+ ### How to integrate re-captcha in Symfony form:
67
+
68
+ ` ` ` php
69
+ <?php
70
+
66
71
use Karser\Recaptcha3Bundle\Form\Recaptcha3Type;
67
72
use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3;
68
73
@@ -78,6 +83,70 @@ class TaskType extends AbstractType
78
83
}
79
84
```
80
85
86
+ ### How to integrate re-captcha in API method:
87
+
88
+ The idea is to require the frontend to submit the captcha token, so it will be validated on server side.
89
+
90
+ First you need to add the captcha field to your transport entity:
91
+ ``` php
92
+ <?php
93
+
94
+ namespace App\Dto\UseCases;
95
+
96
+ final class UserSignupRequest
97
+ {
98
+ /** @var string|null */
99
+ public $email;
100
+
101
+ /** @var string|null */
102
+ public $captcha;
103
+ }
104
+ ```
105
+
106
+ And to add the validation constraint:
107
+
108
+ ``` yaml
109
+ # config/validator/validation.yaml
110
+ App\Dto\UserSignupRequest :
111
+ properties :
112
+ email :
113
+ - NotBlank : ~
114
+ - Email : { mode: strict }
115
+ captcha :
116
+ - Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3 : ~
117
+ ` ` `
118
+
119
+
120
+ On frontend part you need to submit the captcha token along with email.
121
+ You can obtain the captcha token either *on page load* or *on form submit*.
122
+
123
+ ` ` ` html
124
+ <script src="https://www.google.com/recaptcha/api.js?render=<siteKey>"></script>
125
+
126
+ <script>
127
+ const siteKey = '*****************-**-******-******';
128
+
129
+ //either on page load
130
+ grecaptcha.ready(function() {
131
+ grecaptcha.execute(siteKey, {
132
+ action : ' signup|resend_email|forgot_password'
133
+ }).then(function(token) {
134
+ //the token will be sent on form submit
135
+ $('[name="captcha"]').val(token);
136
+ });
137
+ });
138
+
139
+ //or on form post :
140
+ grecaptcha.ready(function() {
141
+ grecaptcha.execute(siteKey, {
142
+ action : ' signup|resend_email|forgot_password'
143
+ }).then(function(token) {
144
+ //submit the form
145
+ return http.post(url, {email, captcha : token});
146
+ });
147
+ });
148
+ </script>
149
+ ```
81
150
82
151
Testing
83
152
-------
0 commit comments