
本文详解 react 项目中调用 msg91 otp 验证接口的完整实现,重点解决因认证方式错误(将 authkey 放入 url 而非请求头)和参数传递方式不匹配导致的 “invalid auth key” 错误。
本文详解 react 项目中调用 msg91 otp 验证接口的完整实现,重点解决因认证方式错误(将 authkey 放入 url 而非请求头)和参数传递方式不匹配导致的 “invalid auth key” 错误。
在 React 应用中集成 MSG91 的 OTP 验证功能时,一个常见却隐蔽的错误是:将 authkey 直接拼接在目标 URL 查询参数中。MSG91 官方 API 明确要求 authkey 必须通过 HTTP 请求头(authkey 字段)传递,而非 URL 参数——否则服务端会直接拒绝请求并返回 Invalid Auth key,即使密钥本身完全正确。
✅ 正确的代理配置(setupProxy.js)
需使用 http-proxy-middleware 将前端 /api/verifyOTP 请求代理至 MSG91 接口,并通过 headers 选项注入认证信息:
// src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
const MSG91_AUTHKEY = 'YOUR_MSG91_AUTH_KEY_HERE'; // ✅ 替换为你的真实 authkey
module.exports = function(app) {
app.use(
'/api/verifyOTP',
createProxyMiddleware({
target: 'https://www.php.cn/link/d6da07889d94ee6609a9d2624077b3c5/api/v5/otp/verify',
changeOrigin: true,
pathRewrite: (path, req) => {
const mobile = req.query.mobile || '';
const otp = req.query.otp || '';
// ✅ 构造查询字符串:mobile 和 otp 保留在 URL 中(MSG91 要求)
return `?mobile=91${mobile}&otp=${otp}`;
},
headers: {
authkey: MSG91_AUTHKEY, // ✅ 关键:authkey 必须在此处以 header 形式传递
},
onProxyReq: (proxyReq, req, res) => {
// 可选:调试日志,确认 header 已设置
console.log('Proxying with authkey header:', MSG91_AUTHKEY);
}
})
);
};⚠️ 注意事项:
- pathRewrite 中必须返回完整查询字符串(如 ?mobile=...&otp=...),而非 &mobile=...&otp=...(否则 URL 拼接错误);
- 不要将 authkey 写入 target URL(如 ?authkey=...),这将被忽略且触发鉴权失败;
- 确保 authkey 值无空格、换行或隐藏字符,建议从 MSG91 控制台复制纯文本。
✅ 前端调用逻辑(App.js 或组件中)
使用 fetch 发起 GET 请求,仅通过 URL 传入 mobile 和 otp(无需 request body,也不需要额外 headers):
// 示例:在函数组件中
const [mobile, setMobile] = useState('');
const [otp, setOtp] = useState('');
const verifyOTP = async () => {
if (!mobile || !otp) return;
try {
const response = await fetch(`/api/verifyOTP?mobile=${mobile}&otp=${otp}`, {
method: 'GET',
// ❌ 不要在这里加 headers: { 'authkey': ... } —— 代理层已处理
});
const data = await response.json();
if (response.ok && data.type === 'success') {
console.log('✅ OTP verified successfully');
alert('Verification successful!');
} else {
console.error('❌ Verification failed:', data.message || data);
alert(`Verification failed: ${data.message || 'Unknown error'}`);
}
} catch (err) {
console.error('⚠️ Network or parsing error:', err);
alert('Network error. Please try again.');
}
};
// JSX
<input
placeholder="Enter mobile (e.g., 9876543210)"
value={mobile}
onChange={(e) => setMobile(e.target.value)}
/>
<input
placeholder="Enter OTP"
value={otp}
onChange={(e) => setOtp(e.target.value)}
/>
<button onClick={verifyOTP}>Verify OTP</button>? 验证与调试建议
- 使用浏览器开发者工具 → Network 标签页,检查 /api/verifyOTP 请求:
- Request URL 应含 ?mobile=91...&otp=...
- Request Headers 中应包含 authkey: YOUR_ACTUAL_KEY
- 对比 MSG91 文档中的 cURL 示例,确保行为一致;
- 若仍报错,请登录 MSG91 控制台 确认:
- Auth Key 是否处于 Active 状态;
- 所用模板 ID(若涉及)是否与发送 OTP 时一致(验证接口本身不依赖 template_id);
- 账户余额及 OTP 服务是否启用。
遵循以上配置后,React 前端即可安全、合规地完成 MSG91 OTP 验证流程,彻底规避 Invalid Auth key 类错误。


















