Skip to content

Instantly share code, notes, and snippets.

@luckylooke
Created August 21, 2019 13:24
Show Gist options
  • Save luckylooke/847b61ced8e4bf706d5c2f3ac83d43fa to your computer and use it in GitHub Desktop.
Save luckylooke/847b61ced8e4bf706d5c2f3ac83d43fa to your computer and use it in GitHub Desktop.
Google recaptcha wrapper for grecaptcha.execute() with version 2 fallback.
function execute(action, callback) {
// create real promise, because execute method does not return the real one
// (missing documentation what actually returns)
const promise = new Promise((resolve, reject) => {
grecaptcha.ready(() =>
grecaptcha.execute(key, { action }).then(token => {
resolve(token);
},
reject)
);
})
.then(token => callback(token, false)) // v3 token
.catch(err => {
const transformedErr = errorService.transformError(err); process error from backend
if (transformedErr.type === 'reCaptcha') { // v3 was unsuccessful, fallback to v2 to give user chance to prove his humanity
return renderV2().then(token => callback(token, true));
}
// else errors rethrow to continue to other catches
throw err;
});
return promise;
}
function renderV2() {
const promise = new Promise((resolve, reject) => {
grecaptcha.ready(() => {
grecaptcha.render('recaptcha-container', {
sitekey: keyV2,
callback: resolve,
'expired-callback': () => {
grecaptcha.reset('recaptcha-container');
},
'error-callback': reject,
});
});
});
return promise;
////////////////////////////////////////////////////////////////////////////////////////
// Example of usage ////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
function checkName(name) {
return execute('check', (reCapToken, V2) =>
axios
.get('/check', {
params: {
login,
reCapToken,
reCaptV2: V2,
},
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment