You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS集成MSG91验证OTP时提示无效密钥的问题排查

解决MSG91 OTP验证时的「Invalid Auth key」错误

问题根源分析

你的代码存在几个关键问题导致Auth key验证失败:

  1. 请求方法不匹配:MSG91的OTP验证接口要求使用POST请求,你当前用了GET,且试图从req.body获取参数(GET请求无请求体),导致参数传递异常。
  2. Proxy参数拼接逻辑错误:setupProxy.js中pathRewrite尝试从请求体拿mobile和otp,但GET请求没有body,这两个参数会为空,同时拼接方式会导致最终请求的参数格式混乱。
  3. Content-Type设置错误:GET请求不需要设置Content-Type: application/json,反而会让接口解析逻辑异常。

修复方案及代码调整

1. 修改App.js中的verifyOTP函数

将请求改为POST,把参数放在请求体中,而非URL query:

<button onClick={verifyOTP}>Verify OTP</button>

const verifyOTP = async () => {
  const mobileNumber = mobile;

  try {
    const response = await fetch('/api/verifyOTP', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        mobile: `91${mobileNumber}`,
        otp: otp
      })
    });

    if (response.ok) {
      const responseData = await response.json();

      if (responseData.type === 'success' && responseData.message === 'OTP verified successfully') {
        console.log('OTP Verified Successfully');
      } else {
        console.error('Failed to verify OTP:', responseData.message);
      }
    } else {
      console.error('Error verifying OTP. Status code:', response.status);
    }
  } catch (error) {
    console.error('Error verifying OTP:', error);
  }
};

2. 调整setupProxy.js配置

改为支持POST请求,正确传递Auth key和请求参数:

const { createProxyMiddleware } = require('http-proxy-middleware');

const authKey = 'xxxxxxxxxxxxxxxxxx'; 

module.exports = function(app) {
  app.use(
    '/api/verifyOTP',
    createProxyMiddleware({
      target: 'https://control.msg91.com/api/v5/otp/verify',
      changeOrigin: true,
      methodFilter: ['POST'],
      pathRewrite: {
        '^/api/verifyOTP': ''
      },
      onProxyReq: (proxyReq, req, res) => {
        // 将Auth key添加到请求的query参数中
        const url = new URL(proxyReq.path, proxyReq.protocol + '//' + proxyReq.host);
        url.searchParams.append('authkey', authKey);
        proxyReq.path = url.pathname + url.search;

        // 处理POST请求体,确保参数正确传递
        if (req.body) {
          const bodyData = JSON.stringify(req.body);
          proxyReq.setHeader('Content-Type', 'application/json');
          proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
          proxyReq.write(bodyData);
          proxyReq.end();
        }
      }
    })
  );
}

额外验证点

  • 确认你的Auth key是MSG91控制台中OTP服务对应的有效密钥,而非其他服务的密钥。
  • 检查手机号格式是否正确(必须带国家码91,且无多余符号)。
  • 确保OTP是最近发送的未过期验证码。

内容的提问来源于stack exchange,提问作者puja singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 04:26:23