--- tags: Laravel --- # 處理Google reCAPTCHA 送出的 timeout 問題 ## reCAPTCHA token的有限時間只有2分鐘 > reCAPTCHA tokens expire after two minutes. If you're protecting an action with reCAPTCHA, make sure to call execute when the user takes the action rather than on page load. --- ### 處理方式 1 ```php= <form> <input type="hidden" name="recaptcha" id="recaptcha"> <button>Submit</button> </form> <script> const btn = document.querySelector('button'); const form = document.querySelector('form'); btn.addEventListener('click', () => { grecaptcha .execute('{{ config('services.recaptcha.sitekey') }}', {action: 'subscribe'}) .then(function(token) { if(token) { document.getElementById('recaptcha').value = token; form.submit(); } }); }); ``` ```php= $('#user_register').submit(function(e) { e.preventDefault(); grecaptcha.execute() .then(function(token) { // your ajax code goes here }); }); ``` --- ### 處理方式 2 ```php= <script> grecaptcha.ready(function() { document.getElementById('contactform').addEventListener("submit", function(event) { event.preventDefault(); grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) { document.getElementById("googletoken").value = token; document.getElementById('contactform').submit(); }); }, false); }); </script> ``` --- ### 處理方式 3 ```html= <form method="POST" action="{{ route('login') }}" onsubmit="refreshReCaptcha()" name="formLogin" id="formLogin"> ... </form> <script> function refreshReCaptcha() { event.preventDefault(); //更新 Google ReCaptcha grecaptcha.execute('{{ env('RECAPTCHA_V3_SITE_KEY') }}', {action: 'login'}).then(function(token) { document.getElementById('login_id').value = token; document.getElementById('formLogin').submit(); }); } </script> ``` --- ### 處理方式 4 >當使用 laravel-google-recaptcha-v3 套件 ```javascript= <script> setInterval(function () { refreshReCaptchaV3('contact_subscribe_id', 'contact_subscribe'); }, 120000); </script> ``` --- ### 處理方式 5 >當使用 laravel-google-recaptcha-v3 套件 ```html= <form method="POST" action="{{ route('enroll') }}" onsubmit="refreshBeforeSubmit()" name="formEnroll" id="formEnroll"> ... </form> {!! GoogleReCaptchaV3::renderOne('enroll_id','enroll') !!} <script> //更新 Google ReCaptcha function refreshBeforeSubmit() { event.preventDefault(); refreshReCaptchaV3('enroll_id', 'enroll').then(function () { document.getElementById('formEnroll').submit(); }); } </script> ```