
本文详解如何在 react 项目中使用 msg91 的 otp 验证 api,重点解决因认证方式错误(如将 authkey 放入 url 而非请求头)导致的 “invalid auth key” 报错问题,并提供代理配置、前端调用及注意事项。
本文详解如何在 react 项目中使用 msg91 的 otp 验证 api,重点解决因认证方式错误(如将 authkey 放入 url 而非请求头)导致的 “invalid auth key” 报错问题,并提供代理配置、前端调用及注意事项。
在 React 中集成 MSG91 的 OTP 验证功能时,一个常见但易被忽视的关键点是:MSG91 v5 API 要求 authkey 必须通过 HTTP 请求头(authkey 字段)传递,而非拼接在 URL 查询参数中。若错误地将 authkey 放入目标 URL(如 ?authkey=xxx),服务端会拒绝请求并返回 Invalid Auth key 错误——即使密钥本身完全正确。
✅ 正确的代理配置(setupProxy.js)
需确保 http-proxy-middleware 将 authkey 作为请求头注入,同时从查询参数(而非请求体)提取 mobile 和 otp:
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,
pathRewrite: (path, req) => {
const mobile = req.query.mobile ?? '';
const otp = req.query.otp ?? '';
return `?mobile=91${mobile}&otp=${otp}`;
},
headers: {
authkey: 'YOUR_MSG91_AUTH_KEY_HERE', // ⚠️ 替换为真实 Auth Key
},
onProxyReq: (proxyReq, req, res) => {
// 确保不携带原始 Origin 头(避免跨域干扰)
proxyReq.removeHeader('origin');
}
})
);
};? 注意:pathRewrite 返回的是完整查询字符串(以 ? 开头),而非 &;req.query 才能正确读取 GET 请求的 URL 参数。
✅ 前端调用方式(App.js)
使用 fetch 发起 GET 请求,将 mobile 和 otp 作为 URL 查询参数传入(符合 MSG91 文档要求),无需设置请求体或额外 header:
const verifyOTP = async () => {
if (!mobile || !otp) return;
try {
const response = await fetch(`/api/verifyOTP?mobile=${mobile}&otp=${otp}`, {
method: 'GET',
// ❌ 不要在此处添加 authkey header —— 代理层已自动注入
headers: {
'Content-Type': 'application/json', // 可选,GET 请求通常无需 body
},
});
const data = await response.json();
if (response.ok && data.type === 'success') {
console.log('✅ OTP verified successfully');
alert('Verification successful!');
} else {
console.error('❌ OTP verification failed:', data.message || 'Unknown error');
alert(`Verification failed: ${data.message || 'Please check mobile & OTP'}`);
}
} catch (error) {
console.error('⚠️ Network or parsing error:', error);
alert('Network error. Please try again.');
}
};
// JSX 中调用
<button onClick={verifyOTP} disabled={!mobile || !otp}>
Verify OTP
</button>⚠️ 关键注意事项
- Auth Key 安全性:setupProxy.js 运行在开发服务器端(Node.js),因此 authkey 不会暴露给浏览器,这是安全的。切勿在前端代码中硬编码或通过 fetch 直接发送 authkey。
- 手机号格式:MSG91 要求 mobile 参数为 10 位纯数字(不含国家码),代理中已自动补 91 前缀;请确保用户输入的 mobile 是如 9876543210 的格式。
- API 版本与文档:务必参考 MSG91 Verify OTP 官方文档(v5),确认字段名(如 mobile、otp)、响应结构(data.type, data.message)及状态码含义。
- 生产环境适配:setupProxy.js 仅用于 create-react-app 开发环境。上线时需由 Nginx 或后端服务(如 Express)统一代理,同样需在转发请求时注入 authkey 请求头。
遵循以上配置,即可稳定、安全地完成 OTP 验证流程,彻底规避 Invalid Auth key 类错误。


















