recaptcha-v3-verify
Version:
A TypeScript npm plugin for verifying reCAPTCHA tokens.
50 lines (49 loc) • 1.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyRecaptcha = verifyRecaptcha;
async function verifyRecaptcha(secret, response, remote_ip) {
var _a;
const url = 'https://www.google.com/recaptcha/api/siteverify';
try {
const params = new URLSearchParams({
secret,
response,
...(remote_ip ? { remoteip: remote_ip } : {}),
});
const result = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
// Check if the HTTP response is OK (status 200-299)
if (!result.ok) {
console.error(`HTTP error! status: ${result.status}`);
return {
success: false,
error_message: `HTTP error! status: ${result.status}`,
};
}
const data = await result.json();
// Check if the reCAPTCHA verification was unsuccessful
if (!data.success) {
const errorCodes = ((_a = data['error-codes']) === null || _a === void 0 ? void 0 : _a.join(', ')) || 'Unknown error';
return {
...data,
error_message: `reCAPTCHA verification failed: ${errorCodes}`,
};
}
// Success case
return data;
}
catch (error) {
console.error('Failed to verify reCAPTCHA:', error);
return {
success: false,
error_message: 'An unexpected error occurred while verifying the reCAPTCHA token.',
};
}
}
// Export for both ESM and CommonJS environments
module.exports = { verifyRecaptcha };