
本文详解 react 项目中通过代理方式安全调用 msg91 otp 验证 api 的完整方案,重点解决因认证方式错误(如将 authkey 放入 url)导致的 “invalid auth key” 错误,并提供可运行的 proxy 配置与前端调用示例。
本文详解 react 项目中通过代理方式安全调用 msg91 otp 验证 api 的完整方案,重点解决因认证方式错误(如将 authkey 放入 url)导致的 “invalid auth key” 错误,并提供可运行的 proxy 配置与前端调用示例。
MSG91 的 OTP 验证接口(/api/v5/otp/verify)严格要求 authkey 必须通过 HTTP 请求头(authkey header)传递,而非拼接在 URL 查询参数中。这是绝大多数开发者遇到 Failed to verify OTP: Invalid Auth key 错误的根本原因——即使密钥本身完全正确,只要位置错误,服务端就会拒绝认证。
此外,原代码中存在多个关键不匹配:
- 前端 fetch 使用 GET 方法并把 mobile 和 otp 放在 URL 查询参数中;
- 但 setupProxy.js 中却尝试从 req.body 读取参数(而 GET 请求无 body),且 pathRewrite 返回的路径格式也不符合 MSG91 接口规范(多余 & 导致 URL 错误);
- target URL 错误地将 authkey 写入了目标地址,使代理无法动态注入请求头。
✅ 正确做法如下:
1. 修正 setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api/verifyOTP',
createProxyMiddleware({
target: 'https://control.msg91.com/api/v5/otp/verify',
changeOrigin: true,
// ✅ 从 query 参数提取 mobile & otp,构造标准 MSG91 查询字符串
pathRewrite: (path, req) => {
const mobile = req.query.mobile || '';
const otp = req.query.otp || '';
return `?mobile=${mobile}&otp=${otp}`;
},
// ✅ 关键:通过 headers 注入 authkey(注意字段名小写,MSG91 文档明确要求为 'authkey')
headers: {
authkey: 'YOUR_MSG91_AUTH_KEY_HERE', // 替换为你的真实 Auth Key
},
// 可选:添加 Accept 头确保 JSON 响应
onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader('accept', 'application/json');
}
})
);
};
⚠️ 注意事项:
- authkey 是区分大小写的请求头字段,必须为全小写 authkey(非 AuthKey 或 AUTHKEY);
- 不要将 authkey 写进 target URL,否则会被忽略或触发安全拦截;
- mobile 参数需为完整国际格式(如 919876543210),前端传入时请确保已补 91 前缀(或后端统一处理)。
2. 前端调用保持简洁(GET + query)
const verifyOTP = async () => {
if (!mobile || !otp) return;
try {
const response = await fetch(`/api/verifyOTP?mobile=91${mobile}&otp=${otp}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
// ❌ 不需要在此处传 authkey —— 代理层已统一注入
},
});
const data = await response.json();
if (response.ok && data.type === 'success') {
console.log('✅ OTP verified successfully');
// 例如跳转、更新 UI 状态等
} else {
console.error('❌ OTP verification failed:', data.message || 'Unknown error');
}
} catch (err) {
console.error('⚠️ Network or parsing error:', err);
}
};
// JSX 中使用
<button onclick="{verifyOTP}" disabled>
Verify OTP
</button>
3. 验证与调试建议
- 在浏览器 DevTools 的 Network 标签中检查 /api/verifyOTP 请求:
- Request Headers 应包含 authkey: YOUR_KEY;
- Request URL 应形如 /api/verifyOTP?mobile=919876543210&otp=123456;
- 使用 curl 手动验证(替换为你的真实值):
curl --request GET \ --url 'https://control.msg91.com/api/v5/otp/verify?mobile=919876543210&otp=123456' \ --header 'accept: application/json' \ --header 'authkey: YOUR_MSG91_AUTH_KEY' - 若仍报错,请确认:
- Auth Key 是否为 v5 版本(旧 v3 Key 不兼容);
- 模板 ID 仅用于发送,验证接口无需模板 ID;
- OTP 是否在有效期内(默认 5 分钟),且未被重复使用。
遵循以上配置,即可在 React 开发环境中安全、可靠地完成 MSG91 OTP 验证,彻底规避认证失败问题。











