세일즈포스 Visualforce에 Google reCAPTCHA 연동하기 - 2부 (Visualforce편)

2025. 7. 26. 17:38·Salesforce/개발_한국어

Salesforce의 Visualforce 페이지에 Google reCAPTCHA를 연동하는 방법을 살펴보도록 하겠습니다. 특히 Web-to-Lead 기능을 구현할 때 스팸 방지와 보안 강화를 위해 꼭 필요한 과정입니다. 이 글은 이미 Web-to-Lead용 Visualforce 페이지를 만들어두셨다는 전제로 진행하겠습니다. 

  • Salesforce 관리자(Admin) 화면에서 reCAPTCHA 연동을 위한 기본 세팅.
  • Visualforce 페이지에 reCAPTCHA 구현.

 

보안 세팅

Remote Site Settings

Remote Site Settings

Remote Site Settings로 이동 -> New를 눌러 새로운 정보를 생성합니다.

  • URL: https://www.google.com/

 

Trusted URLs

Trusted URLs

Trusted URLs로 이동 -> New를 눌러 새로운 정보를 생성합니다.

  • URL: https://www.google.com/

 

Sites

Clickjack Protection Level

Sites로 이동하여 Visualforce가 등록되어 있는 사이트의 상세페이지로 이동합니다.

Edit을 눌러 Clickjack Protection Level의 수준을 Allow framing by any page (No protection)로 변경합니다.

 

Visualforce & Apex 흐름도

 

Visualforce와 Apex간의 흐름을 그려보았습니다.

최대한 불필요한 과정들을 제거하여 필수적이라고 판단되는 부분들만 구현하였습니다.

 

Visualforce에 구현하기

HTML 영역

reCAPTCHA를 어디에 노출하고 어떤 액션이 발생하였을 때 reCAPTCHA를 발생시킬건지 고민할 필요가 없습니다.

경험에 비추어 보았을 때 일반적으로 사이트에 처음 접속했을때나 폼(Form)을 작성해서 제출할 때 발생시키고 있습니다.

저또한 폼을 작성하고 제출할 때 reCAPTCHA 로직을 실행시키는 방향으로 설계하였습니다.

 

<apex:form id="leadForm">
	<apex:actionFunction name="submitLeadForm" action="{!createLead}"
		rerender="recaptchaError, globalErrorMessage" oncomplete="handleAjaxComplete(event);"
		status="submitStatus" />

		<div id="step4" class="form-step">
			<apex:inputHidden id="recaptchaToken" value="{!recaptchaToken}" />
			<span id="recaptchaError" class="field-error"></span>

			<div class="button-group">
				<button type="button" class="secondary" onclick="prevStep()">Previous</button>
				<button type="button" class="submit-button" onclick="executeRecaptcha();">Submit</button>
			</div>

			<div class="g-recaptcha" data-sitekey="사이트키" data-size="invisible"></div>
				<p class="recaptcha-info" style="font-size: 0.8em; color: #777; margin-top: 10px;">
					This site is protected by reCAPTCHA and the Google
					<a href="https://policies.google.com/privacy" target="_blank">Privacy Policy</a> and
					<a href="https://policies.google.com/terms" target="_blank">Terms of Service</a> apply.
				</p>
			</div>
 </apex:form>

 

data-sitekey에 본인의 Google reCAPTCHA Site Key를 입력합니다.

이번 포스트에서는 Apex 영역을 다루지 않기에 껍데기만 만들어서 연결해주시면 됩니다.

저는 위 코드를 활용해서 아래와 같은 모습으로 구현하였습니다.

 

Google reCAPTCHA html
버튼 밑에 메시지와 우측에 로고가 추가되었다.

JavaScript

reCAPTCHA 호출하기

<head>
   <script src="https://www.google.com/recaptcha/api.js?render=사이트키"></script>
</head>

헤더에서 스크립트를 통해 api를 호출합니다.

시크릿키는 이전에 발급받은 reCAPTCHA 사이트키를 넣어주시면 됩니다.

 

function getSalesforceId(idEnd) {
            const element = document.querySelector(`[id$="${idEnd}"]`);
            if (!element) {
                console.warn(`Element with ID ending in "${idEnd}" not found.`);
                return null; // Return null if not found
            }
            return element.id; // Return the full Salesforce-generated ID
        }
        
const recaptchaTokenInput = document.getElementById(getSalesforceId('recaptchaToken'));

 

getElemenyById가 생각대로 작동하지 않는 경우가 있습니다.

세일즈포스에서 visualforce의 element id에 고유한 값을 자동으로 넣고 있어 찾지 못하는 경우가 발생합니다.

위 함수를 이용해서 여러분이 입력한 id값을 전달해주면 전달받은 id값으로 끝나는 element를 찾아 전체 id를 반환시켜 줍니다.

 

function executeRecaptcha() {

            // Execute reCAPTCHA v3
            grecaptcha.ready(function() {
                grecaptcha.execute('사이트키', { action: 'submit_lead_form' }).then(function(token) {

                    if (recaptchaTokenInput) {
                        recaptchaTokenInput.value = token;
                        submitLeadForm();
                    } else {
                        console.error('Error: recaptchaTokenInput element not found in DOM.');
                        displayGlobalError('Error: reCAPTCHA setup issue. Please try again.');
                        if (submitButton) submitButton.disabled = false;
                    }
                }).catch(function(error) {
                    console.error('reCAPTCHA execution failed:', error);
                    displayGlobalError('Failed to verify reCAPTCHA. Please try again.');
                    if (submitButton) submitButton.disabled = false;
                });
            });
            return false;
}

 

위의 로직은 단순합니다.

여러분의 사이트키를 이용하여 토큰값을 받아오는 로직입니다.

받아온 토큰값을 recaptchaTokenInput의 value에 할당합니다.

할당해주는 이유는 이 값을 Apex에서 활용하기 위해서 할당하였습니다.

 

 

마무리

다음 포스트에서는 Apex Controller에서 reCAPTCHA 응답 토큰을 받아 Google 서버에 백엔드 검증(verify) 하는 과정을 설명할 예정입니다. 또한, Custom Metadata Types를 활용하여 민감한 키 정보를 안전하게 관리하고 보안성을 향상시키는 방법도 함께 다루고자 합니다.

 

 

출처

https://help.salesforce.com/s/articleView?id=service.workdotcom_quemgmt_set_up_captcha.htm&type=5

 

Help And Training Community

 

help.salesforce.com

 

저작자표시 비영리 변경금지 (새창열림)

'Salesforce > 개발_한국어' 카테고리의 다른 글

세일즈포스 Visualforce에 Google reCAPTCHA 연동하기 - 1부 (개념 및 발급)  (0) 2025.06.06
세일즈포스 Single Sign-on (SSO) 연동하기 (Advanced)  (0) 2025.01.26
Experience Cloud 사이트에 Single Sign-on (SSO) 추가하기  (0) 2025.01.02
LWC Refresh Related List  (2) 2024.10.11
세일즈포스 LWC로 lightning-map 활용한 지도 구현 가이드 (2부)  (0) 2024.08.19
'Salesforce/개발_한국어' 카테고리의 다른 글
  • 세일즈포스 Visualforce에 Google reCAPTCHA 연동하기 - 1부 (개념 및 발급)
  • 세일즈포스 Single Sign-on (SSO) 연동하기 (Advanced)
  • Experience Cloud 사이트에 Single Sign-on (SSO) 추가하기
  • LWC Refresh Related List
세일즈포스 개발 및 어드민 블로그
세일즈포스 개발 및 어드민 블로그
세일즈포스 입문을 도와드릴게요!
  • 세일즈포스 개발 및 어드민 블로그
    Loitering
    세일즈포스 개발 및 어드민 블로그
  • 전체
    오늘
    어제
    • 분류 전체보기 (65)
      • 미국 유학 (1)
      • Salesforce (58)
        • Admin_한국어 (22)
        • 개발_한국어 (16)
        • Admin_English (18)
        • Development_English (2)
      • 여행 (5)
        • 러시아 (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    salesforce dynamic layouts
    apex
    salesforce price
    modal
    salesforce dynamic fields
    세일즈포스
    Illuminated Cloud
    세일즈포스 어드민
    세일즈포스 트레일헤드
    salesforce sso setup
    salesforce deploy
    모스크바 여행
    세일즈포스 써티
    어드민
    salesforce custom notification
    salesforce path assistant
    LWC
    salesforce development
    admin
    translation
    salesforce encrypted fields
    salesforce dynamic forms
    salesforce
    salesforce recaptcha
    러시아 여행
    Salesforce Admin
    development
    세일즈포스 레이아웃
    모스크바 식당
    세일즈포스 개발
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
세일즈포스 개발 및 어드민 블로그
세일즈포스 Visualforce에 Google reCAPTCHA 연동하기 - 2부 (Visualforce편)
상단으로

티스토리툴바