invitation india
UnexpectedWeb
Connect

Popular Technology Blog where you'll find some interesting things around the web, that you never knew existed.

link Link copied

How to add reCaptcha to google apps script

Share on: link Link copied
let's learn how to Integrate reCAPTCHA in Google Apps Script project and done server side validation of user's response.

Google reCAPTCHA is a free service that protects websites or App from spam and automated abuse(bot). So add reCAPTCHA and protect your google apps script web app from spam and invalid request.

Register for Google reCAPTCHA


In order to add Google reCAPTCHA in google app script, we need to register or sign up for getting an API key pair.
  1. Register for reCAPTCHA
  2. Choosing the type of reCAPTCHA:  (reCAPTCHA v2 > "I'm not a robot" Checkbox) 
  3. In the Domains box, enter googleusercontent.com *
  4. Click on the Submit button.
* If you enter googleusercontent.com as a Domains then reCaptcha not restricted to specific appscript webapp domain. In other words, you can use the same reCAPTCHA key for all your google app script projects, even use the same key for different google account also.

But if you want reCAPTCHA will work only for the specific web application, then you can set individual app script domain  also. For that run your application, open DevTools (F12), search "googleusercontent.com" then copy the src of the iframe.
n-eavs5zmfkkivnubksf7ktfpnedq6coxg66obefi-0lu-script.googleusercontent.com

Get google app script web app domain


After the submission Google will generate two key (Site key and Secret key). Site key is used to adding reCAPTCHA on your site or app while secret key is used to velidate the user's response on server (backend).

Integrate reCAPTCHA - Client Side

To adding reCAPTCHA widget on your google apps script Web App's page 

  1. Add the following code inside the <head> section on your HTML page:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

  1. Add the following code inside the <form> where you want display the reCAPTCHA widget
<div class="g-recaptcha" data-sitekey="your_site_key"></div>

Integrate reCAPTCHA - Server Side

Validate user's google captcha response from your web app script. You can verify the response with the server side script by adding this function to your Google Script file (code.gs).

var secret_key = "Your_Secret_Key";  
        
function verifyCaptcha(response){
  var url = 'https://www.google.com/recaptcha/api/siteverify';
  var payload = {
    'secret' : secret_key,
    'response': response['g-recaptcha-response']
  }
 
  var resp = UrlFetchApp.fetch(url, {
    payload : payload,
    method : 'POST'
  }).getContentText();
  return JSON.parse(resp).success;
}        


Live Demo:

Let's create the simple Web App so you will get more clear idea about how to use google reCaptcha in google apps script. In this app we will collect input from users and validate captcha response (on server side) then show the message accordingly.



home.html

  <html>
  <head>
    <base target="_top">
    
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>

    
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
     
     <style>
        .input-field{
          width:304px!important;
        }        
           .input-field input[type=text]:focus + label {
             color: #3f51b5 !important;
        }      
         .input-field input[type=text]:focus {
           border-bottom: 1px solid #3f51b5 !important;
           box-shadow: 0 1px 0 0 #3f51b5 !important;
         }
      </style>
      
  </head>
  
  <body>
     
    <form id='myform' style="padding:22px; width: 350px;" >
    <div class="row">
        <div class="input-field col ">
          <input  name="firstname" type="text">
          <label for="fname">First Name</label> 
        </div> 
     </div> 
     
     <div class="row">
         <div class="input-field col">
          <input name="lastname" type="text">
          <label for="lname">Last Name</label>
        </div> 
     </div>      
     
      <div class="row">
        <div id="recaptcha" class="g-recaptcha" data-sitekey="6LePntgUAAAAAN3lc5kmTRpSlKz7EW6ObD6Nu1Jd"></div>
      </div>
      
      
      <div id='message' style="color: #ec0f5a; padding: 10px; margin-top: -16px; text-align: center; ">  </div> 
      
      
       <div class="row">
        <div id="as" style="margin-left: 70px;" class="waves-effect waves-light btn-large indigo darken-3"  onclick="handleFormSubmit()" ><i class="material-icons left">chevron_right</i>Submit</div> 
     </div>  
        
    </form>
    
    
     
 
 
    <script>
      function ShowResuelt(response){
        document.getElementById('message').innerHTML = response;
      }
      
      function handleFormSubmit() {
        document.getElementById('message').innerHTML = 'wait...';                
        var getForm = document.getElementById('myform');                
        google.script.run.withSuccessHandler(ShowResuelt).processForm(getForm);
      }           
       
    </script>
    
  </body>
</html>


Code.gs

  
function doGet() {  
    return HtmlService.createTemplateFromFile("home").evaluate();  
}  



function processForm(formObj) { 
    var FirstName = formObj.firstname;
    var LastName = formObj.lastname;    
    var validCaptcha = verifyCaptcha(formObj);
    
    if(!validCaptcha){
      return 'Invalid captcha please try againt.';
    } else {
        return "Hi "+FirstName+" "+ LastName+", Thanks for verifying your identity.";
    }     
}  




var secret_key = "6bjYrXXXXXXXX] SecretKey [XXXXXXXXXXr01Ok5";  

        
function verifyCaptcha(response){
  var url = 'https://www.google.com/recaptcha/api/siteverify';  
  var payload = {
    'secret' : secret_key,
    'response': response['g-recaptcha-response']
  } 
  var resp = UrlFetchApp.fetch(url, {
    payload : payload,
    method : 'POST'
  }).getContentText();
  return JSON.parse(resp).success;
} 


sources: http://www.googleappsscript.org/recent-additions/recaptchawithgoogleappsscript

No comments:

Powered by Blogger.