How to add the CAPTCHA functionality in salesforce

CAPTCHA (an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart”) is a type of challenge-response test used in computing to determine whether or not the user is human. It uses the popular reCAPTCHA technology to implement the challenge.

There are times when we need to prevent the spam or garbage data filled by any anonymous then we need to use reCAPTCHA functionality. The reCAPTCHA looks like:

CAPTCHA

It contains random distorted images that is easily read by any human being.

We can use this in salesforce site etc. Lets take an example,a company provide a form for Enquiry,  and if they  needs protection from abuse, it is recommended that they use a reCAPTCHA. With this they ensure that a human was filling in a form before creating a new request for them.

Here I am providing steps to use reCAPTCHA in salesforce :

Step 1 – First we need to get public and private key from the reCAPTCHA site to access this functionality.First we need to sign up for a CAPTCHA key  . After signing up we redirect to the “Create a reCAPTCHA key” page and here you need to enter domail URL and check the “Enable this key on all domains (global key)” option to make it global key which is used by any domain and create keys .To proceed this way you got your public and private key which is further used in apex and VF page.

Step 2 – Now you need to add at remote site setting by which salesforce can invoke code from that particular site.

  • Go to the Setup -> Security Controls -> Remote Site Settings. And add the following URL :https://www.google.com.

RemoteSiteStep 3- Now you have reCAPTCHA key as well as you added remote site settings. At last you need to write down code to achieve the reCAPTCHA functionality.

Apex Code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class EnquiryController {
     private static string secret = 'Copy your private key here.' ;
     public string publicKey { get { return 'Copy your public key here.' ; }}
     private static string baseUrl = 'https://www.google.com/recaptcha/api/verify' ;
     public string challenge {get; set;} { challenge = null ; }
     public string response {get; set; } { response = null ; }
     public Enquiry__c enquiryObj{get;set;}
     public Boolean correctResponse { get; private set; } { correctResponse = false ; }
 
     public EnquiryController() {
         enquiryObj = new Enquiry__c();
     }
 
     public pageReference verifyAndSubmit() {
         if ( challenge == null || response == null ) {
             return null ;
         }
         HttpResponse r = makeRequest( baseUrl , 'privatekey=' + secret +
                                       '&remoteip=' + remoteHost +
                                       '&challenge=' + challenge +
                                       '&response=' + response +
                                       '&error=incorrect-captcha-sol'
                          );
         if ( r != null ) {
             correctResponse = ( r.getBody().contains( 'true' ) );
             if ( correctResponse == true ) {
                 insert enquiryObj;
             } else {
                 ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please fill the value in                                                                   CAPTCHA properly.' );
                 ApexPages.addMessage(myMsg);
                 return NULL;
             }
         }
         return null ;
     }
 
     public static HttpResponse makeRequest(string url, string body) {
         HttpRequest req = new HttpRequest();
         HttpResponse response = null ;
         req.setEndpoint( url );
         req.setMethod( 'POST' );
         req.setBody ( body);
         try {
             Http http = new Http();
             response = http.send(req);
         } catch ( System.Exception e) {
             System.debug( 'ERROR: ' + e);
         }
         return 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;
         }
     }
}

In the above code we need to make a HTTP post with challenge,response ,private key as a parameter  to reCAPTCHA site in the “verifyAndSubmit” method  and the response body contains ‘true’ if the challenge and response is equal otherwise contain false.

And the Visual force page code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<apex:page controller= "EnquiryController" >
     <apex:form>
         <apex:pagemessages></apex:pagemessages>
         <script type= "text/javascript" src= "https://www.google.com/recaptcha/api/js/recaptcha_ajax.js" ></script>
         <script src= "https://code.jquery.com/jquery-1.9.1.min.js" ></script>
         <script type= "text/javascript" >
             jQuery(document).ready(function (){
                 Recaptcha.create( "{!publicKey}" ,
                           "dynamic_recaptcha_1" ,
                 {
                     theme: "red" ,
                     callback: Recaptcha.focus_response_field
                 });
             });
         </script>
         <apex:inputhidden value= "{!challenge}" id= "challenge" />
         <apex:inputhidden value= "{!response}" id= "response" />
         <script type= "text/javascript" >
             function captureResponse(ele) {
                 document.getElementById( '{!$Component.challenge}' ).value =
                                                   document.getElementById( 'recaptcha_challenge_field' ).value;
                 document.getElementById( '{!$Component.response}' ).value =
                                                   document.getElementById( 'recaptcha_response_field' ).value;
            }
         </script>
         <apex:pageblock title= "Enquiry" >
             <apex:pageBlockButtons location= "bottom" >
                 <apex:commandButton value= "Submit" action= "{!verifyAndSubmit}"
                                      onclick= "javascript:captureResponse(this);" />
             </apex:pageblockButtons>
             <apex:pageBlockSection columns= "1" >
                 <apex:inputField value= "{!enquiryObj.First_Name__c}" />
                 <apex:inputField value= "{!enquiryObj.Last_Name__c}" />
                 <apex:inputField value= "{!enquiryObj.Email__c}" />
                 <apex:inputField value= "{!enquiryObj.Enquiry__c}" />
                 <div id= "dynamic_recaptcha_1" style= "padding-left: 120px;" ></div>
             </apex:pageBlockSection>
         </apex:pageblock>
     </apex:form>
</apex:page>

In the VF we need to pass public key to create reCAPTCHA.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值