Using reCaptcha Dynamically in Salesforce

Add Google as a Remote Site in Salesforce
Apex Class:-reCAPTCHA_Controller
public class reCAPTCHA_Controller 
{
public String myfName {get;set;}
public String mylName {get;set;}
public String myEmail {get;set;}

private static String baseUrl = 'https://www.google.com/recaptcha/api/siteverify';

private static String secret = '6LfoXLEUAAAAAMd7SWyR_O050DbTWlrq2NvHaIf5'; // Here, use your secret key.

public String sitekey
{
get
{
return '6LfoXLEUAAAAAJh6uaq8CvfcNahStQ18bGjpx6RG'; //Here, use your site key.
}
}
public String response
{
get
{
return ApexPages.currentPage().getParameters().get('g-recaptcha-response');
}
}

Public String remoteHost
{
get {
String ret = '127.0.0.1';
// also could use x-original-remote-host
Map<String, String> hdrs = ApexPages.currentPage().getHeaders();
if (hdrs.get('x-original-remote-addr')!= null)
ret = hdrs.get('x-original-remote-addr');
else if (hdrs.get('X-Salesforce-SIP')!= null)
ret = hdrs.get('X-Salesforce-SIP');
return ret;
}
}

public PageReference doVerify()
{

system.debug('>>>>baseUrl>>>>'+baseUrl);

system.debug('>>>>secret>>>>'+secret);

system.debug('>>>>response>>>>'+response);

system.debug('>>>>remoteHost>>>>'+remoteHost);

String responseBody = makeRequest(baseUrl, 'secret=' + secret + '&remoteip=' + remoteHost + '&response=' + response);

//String responseBody = makeRequest(baseUrl, 'secret = '+secret + ' & response = '+response);

system.debug('>>>>responseBody>>>>'+responseBody);

String success = getValueFromJson(responseBody, 'success');

system.debug('>>>>Final success Resp>>>>'+success);

if (success.equalsIgnoreCase('true'))
{
Contact con = new Contact(LastName = mylName, FirstName = myfname, email = myemail);
try
{
system.debug('>>>>con>>>>'+con);
insert con;
pagereference p = new pagereference('/'+con.id);
return p;
}
Catch(exception e)
{
ApexPages.Message errorMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Unexpected error while creating contact');
ApexPages.addMessage(errorMsg);
return null;
}
}
else
{
ApexPages.Message errorMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please verify the captcha');
ApexPages.addMessage(errorMsg);
return null;
}
}

private static String makeRequest(string url, string body)
{
system.debug('>>>>url>>>>'+url);
system.debug('>>>>body>>>>'+body);

HttpResponse response = null;
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('POST');
req.setBody(body);
try
{
Http http = new Http();
response = http.send(req);
string strresp=response.getBody();
system.debug('>>>>strresp>>>>'+strresp);
return response.getBody();
}
catch (System.Exception e)
{
System.debug('ERROR: '+e);
}
return '{"success": false}';
}

public static string getValueFromJson(String strJson, String field)
{
System.debug('strJson>>>>'+ strJson);

System.debug('field>>>>'+ field);

JSON2Apex JSObjData=(JSON2Apex) System.JSON.deserialize(strJson, JSON2Apex.class);

System.debug('JSObjData>>>>'+ JSObjData.success);

string success=JSObjData.success;

return success;

}
//Wrapper Class
public class JSON2Apex
{
public string success;
public String challenge_ts;
public String hostname;
}

}
VF Page:-reCapchaVFPage
<apex:page showheader="false"  controller="reCAPTCHA_Controller" > 
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
 <apex:pageBlock > 
         <apex:pageMessages /> 
         <apex:form >   
                <apex:pageBlockSection columns="1" collapsible="true" title="Create Contact useing reCaptcha"> 
                
                     <apex:pageBlockSectionItem >
                            <apex:outputLabel for="inputName" value="First Name"/> <apex:inputText value="{!myfName}" id="inputName"/>
                      </apex:pageBlockSectionItem>
                      <apex:pageBlockSectionItem >
                            <apex:outputLabel for="inputName" value=" Last Name"/> <apex:inputText value="{!mylName}" id="inputName"/>
                     </apex:pageBlockSectionItem> 
                     <apex:pageBlockSectionItem >
                            <apex:outputLabel for="inputEmail" value="Email"/>
                            <apex:inputText value="{!myEmail}" id="inputEmail"/> 
                     </apex:pageBlockSectionItem> 
                     <div class="g-recaptcha" data-sitekey="{!sitekey}"></div> 
                     <script src="https://www.google.com/recaptcha/api.js"></script> <br/> 
                    <apex:commandButton value="Create Contact" action="{!doVerify}"/> 
                </apex:pageBlockSection>
         
          </apex:form> 
 </apex:pageBlock> 
 
</apex:page>
                         

OutPut:-

Leave a Reply