单页多表单显式渲染Google reCAPTCHA遇「Invalid key type」问题
排查单页多表单reCAPTCHA「Invalid key type」错误方案
核心原因
「Invalid key type」本质是reCAPTCHA脚本版本与密钥类型不匹配:你当前使用的是Enterprise版脚本(enterprise.js),但密钥可能是普通reCAPTCHA v2/v3的;或者密钥是Enterprise版,但脚本调用逻辑存在疏漏。
分步排查与修复
1. 确认密钥与脚本版本匹配
- 登录Google reCAPTCHA管理后台,查看密钥所属类型:
- 如果是普通reCAPTCHA v2/v3密钥:
- 替换页面中的脚本为普通版:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script> - 同时将所有
grecaptcha.enterprise调用改为grecaptcha
- 替换页面中的脚本为普通版:
- 如果是reCAPTCHA Enterprise密钥:
- 确认密钥是在「reCAPTCHA Enterprise」项目下创建的(而非普通reCAPTCHA面板)
- 检查Google Cloud控制台中该项目是否已启用reCAPTCHA Enterprise API
- 如果是普通reCAPTCHA v2/v3密钥:
2. 修正多表单的验证逻辑
原代码存在重复绑定submit事件、回调函数不匹配的问题,以下是优化后的完整实现:
HTML部分(以Enterprise版为例)
<head> <script src="https://www.google.com/recaptcha/enterprise.js?onload=CaptchaCallback&render=explicit" async defer></script> </head> <body> <form id="contactFrm1"> <input type="text" required> <div id="RecaptchaField1" class="g-recaptcha"></div> <button type="submit">提交表单1</button> </form> <form id="contactFrm2"> <input type="email" required> <div id="RecaptchaField2" class="g-recaptcha"></div> <button type="submit">提交表单2</button> </form> </body>
JavaScript部分
// 全局回调,显式渲染所有reCAPTCHA组件 var CaptchaCallback = function() { jQuery('.g-recaptcha').each(function(index, el) { // 为每个组件绑定独立的回调函数 var callbackName = 'formSubmit' + (index + 1); var widgetId = grecaptcha.enterprise.render(el, { 'sitekey': '你的Enterprise密钥', 'callback': callbackName }); jQuery(this).attr('data-widget-id', widgetId); // 动态创建对应表单的回调函数 window[callbackName] = function() { jQuery(el).closest('form').submit(); } }); }; jQuery(document).ready(function() { // 表单1提交拦截 $('#contactFrm1').submit(function(event) { var widgetId = jQuery('#RecaptchaField1').attr('data-widget-id'); if (!grecaptcha.enterprise.getResponse(widgetId)) { event.preventDefault(); grecaptcha.enterprise.execute(widgetId); } }); // 表单2提交拦截 $('#contactFrm2').submit(function(event) { var widgetId = jQuery('#RecaptchaField2').attr('data-widget-id'); if (!grecaptcha.enterprise.getResponse(widgetId)) { event.preventDefault(); grecaptcha.enterprise.execute(widgetId); } }); });
3. 额外检查项
- 确保密钥的「域名验证」已添加当前网站域名(包括子域名)
- 清除浏览器缓存,避免旧脚本缓存导致的异常
- 查看浏览器控制台,排查是否有密钥未注入、脚本加载失败等其他报错
内容的提问来源于stack exchange,提问作者Filadelfo
相关产品推荐
相关产品推荐

