Description:
This article provides a step-by-step guide for integrating Google reCAPTCHA v3 into Login and Registration pages in SuiteCommerce to prevent automated and bot-driven activities. The implementation covers frontend token generation, passing the token to backend SuiteScript 2.0 for verification, and ensuring only valid requests proceed.
Step-by-Step Process
1. Configure Google reCAPTCHA
- Visit the Google reCAPTCHA admin console and register your site.
- Choose reCAPTCHA v3 and generate your Site Key and Secret Key.
- Save the keys for later use in your frontend and backend configurations.
2.Frontend Implementation
Extend Login Register Login View to Add reCAPTCHA Token Generation:
- Extend the login view to include the reCAPTCHA token generation logic during the form submission.
Here’s the frontend code for extending :
_.extend(LoginRegisterLoginView.prototype, {
template: jj_login_register_login_tpl, // Use custom template with reCAPTCHA elements
throwError: function (message, type, container) {
try {
var global_view_message = new GlobalViewsMessageView({
message: message,
type: type || 'error',
closable: true,
});
container.html(global_view_message.render().$el.html());
} catch (error) {
console.log("Error @ throwError:", error);
}
},
events: _.extend({}, LoginRegisterLoginView.prototype.events, {
'submit form': 'submitForm',
}),
submitForm: function (e, model, props) {
var googleRecaptchaModel = new googleRecaptchaModelSS2new();
e.preventDefault(); // Prevent default form submission
const self = this;
const data = jQuery(e.target).closest('form').serializeObject(); // Capture form data
try {
grecaptcha.ready(function () {
grecaptcha.execute(Login_sitekey, { action: 'submit' }).then(function (token) {
googleRecaptchaModel.save({
id: token, // Pass the generated token
})
.done(function (response) {
if (response.success && response.score >= thresholdscore) {
self.saveForm(e, model, props); // Proceed with the form submission
} else {
self.throwError(
"Recaptcha verification failed!!",
"error",
jQuery(".recapcha-message-placer-login")
);
}
})
.fail(function (error) {
console.error("Error during reCAPTCHA verification:", error);
self.throwError(
"An error occurred during reCAPTCHA verification.",
"error",
jQuery(".recapcha-message-placer-login")
);
});
});
});
} catch (error) {
console.log("Error @ saveForm:", error);
}
},
getContext: _.wrap(LoginRegisterLoginView.prototype.getContext, function (fn) {
let originalRet = fn.apply(this, _.toArray(arguments).slice(1));
let ReCaptchaSiteKeyLogin = Login_sitekey; // Use site key
originalRet.ReCaptchaSiteKeyLogin = ReCaptchaSiteKeyLogin;
if (recaptchaOptionEnable) {
originalRet.recaptchaOptionEnable = true;
}
return originalRet;
}),
});
Template Addition:
- Add the reCAPTCHA script and elements in the custom template:
<div id="captcha">
<script src="https://www.google.com/recaptcha/api.js?render={{ReCaptchaSiteKeyLogin}}"></script>
<div class="g-recaptcha-main">
<div class="captcha g-recaptcha" data-sitekey={{ReCaptchaSiteKeyLogin}} style="opacity: 0;">
</div>
<span class="g-recaptcha-error-msg" style="color:red"></span>
</div>
</div>
Backend Implementation
SuiteScript 2.0 Logic for reCAPTCHA Verification:
- Use SuiteScript 2.0 to validate the reCAPTCHA token by sending it to Google’s verification API
Here’s the SuiteScript 2.0 code:
/**
* @NApiVersion 2.x
* @NModuleScope Public
*/
define(['N/https', 'N/log'], function (https, log) {
"use strict";
function service(ctx) {
try {
// Retrieve the token sent from the frontend
var token = ctx.request.parameters ? (ctx.request.parameters.internalid) : null;
log.debug({
title: "Received Token",
details: token
});
var secretKey = 'YOUR_SECRET_KEY'; // Replace with your secret key
// Validate if token exists
if (!token) {
ctx.response.write(JSON.stringify({
success: false,
message: 'Missing token'
}));
return;
}
// Call Google reCAPTCHA API
var response = https.post({
url: 'https://www.google.com/recaptcha/api/siteverify',
body: {
secret: secretKey,
response: token
}
});
var body = JSON.parse(response.body); // Parse API response
ctx.response.setHeader('Content-Type', 'application/json');
ctx.response.write(JSON.stringify({
success: body.success || false,
score: body.score || 0.0
}));
} catch (e) {
log.error('Error during reCAPTCHA validation', e);
ctx.response.setHeader('Content-Type', 'application/json');
ctx.response.write(JSON.stringify({
success: false,
message: 'Error during verification'
}));
}
}
return {
service: service
};
});
Testing
- Load the Login or Registration page and ensure reCAPTCHA is initialized.
- Attempt form submission and verify that:
- Tokens are generated and sent to the backend.
- Backend validation is working, returning and .
- Simulate invalid requests to confirm error handling
Deployment
Replace placeholders (, ) with your actual keys.
Deploy the changes to the appropriate environment (development, staging, or production).